import slugify from "slugify"
import { z } from "zod"

import { nullableArrayObjectValidator } from "@/utils/zod/arrayValidator"
import { nullableStringValidator } from "@/utils/zod/stringValidator"

import { FacilityEnum } from "@/types/enums/facilities"

const rawDetailedFacilitySchema = z.object({
  filter: nullableStringValidator,
  icon: nullableStringValidator,
  id: z.nativeEnum(FacilityEnum),
  name: nullableStringValidator,
  public: z.boolean(),
  sortOrder: z.number(),
})

function transformDetailedFacility(
  data: z.output<typeof rawDetailedFacilitySchema>
) {
  return {
    ...data,
    slug: slugify(data.name, { lower: true, strict: true }),
  }
}

export const detailedFacilitySchema = rawDetailedFacilitySchema.transform(
  transformDetailedFacility
)

export const detailedFacilitiesSchema = nullableArrayObjectValidator(
  rawDetailedFacilitySchema
).transform((facilities) =>
  facilities
    .sort((a, b) => b.sortOrder - a.sortOrder)
    .map(transformDetailedFacility)
)
