import { z } from "zod"

import { imageSchema } from "@/server/routers/hotels/schemas/image"

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

const minMaxSchema = z.object({
  max: z.number(),
  min: z.number(),
})

const bedTypeSchema = z.object({
  description: nullableStringValidator,
  type: nullableStringValidator,
  widthRange: minMaxSchema,
})

const occupancySchema = z.object({
  adults: z.number(),
  children: z.number(),
  total: z.number(),
})

const roomContentSchema = z.object({
  images: z
    .array(imageSchema)
    .nullish()
    .transform((arr) => (arr ? arr.filter(Boolean) : [])),
  texts: z.object({
    descriptions: z.object({
      medium: nullableStringValidator,
      short: nullableStringValidator,
    }),
  }),
})

const roomTypesSchema = z.object({
  code: nullableStringValidator,
  description: nullableStringValidator,
  fixedExtraBed: bedTypeSchema,
  isLackingCribs: z.boolean(),
  isLackingExtraBeds: z.boolean(),
  mainBed: bedTypeSchema,
  name: nullableStringValidator,
  occupancy: occupancySchema,
  roomCount: z.number(),
  roomSize: minMaxSchema,
})

const roomFacilitiesSchema = z.object({
  availableInAllRooms: z.boolean(),
  icon: z.string().optional(),
  isUniqueSellingPoint: z.boolean(),
  name: z.string(),
  sortOrder: z.number(),
})

export const roomCategoriesSchema = z.object({
  attributes: z.object({
    content: roomContentSchema,
    name: nullableStringValidator,
    occupancy: minMaxSchema,
    roomFacilities: nullableArrayObjectValidator(roomFacilitiesSchema),
    roomSize: minMaxSchema,
    roomTypes: nullableArrayObjectValidator(roomTypesSchema),
    sortOrder: z.number(),
  }),
  id: z.string(),
  type: z.literal("roomcategories"),
})

export function transformRoomCategories(
  data: z.output<typeof roomCategoriesSchema>
) {
  return {
    descriptions: data.attributes.content.texts.descriptions,
    id: data.id,
    images: data.attributes.content.images,
    name: data.attributes.name,
    occupancy: data.attributes.occupancy,
    roomFacilities: data.attributes.roomFacilities,
    roomSize: data.attributes.roomSize,
    roomTypes: data.attributes.roomTypes,
    sortOrder: data.attributes.sortOrder,
    type: data.type,
    totalOccupancy:
      data.attributes.occupancy.min === data.attributes.occupancy.max
        ? {
            max: data.attributes.occupancy.max,
            range: `${data.attributes.occupancy.max}`,
          }
        : {
            max: data.attributes.occupancy.max,
            range: `${data.attributes.occupancy.min}-${data.attributes.occupancy.max}`,
          },
  }
}
