import { z } from "zod"

import { BlocksEnums } from "@/types/enums/blocks"
import { Country } from "@/types/enums/country"

export const locationFilterSchema = z
  .object({
    country: z.nativeEnum(Country).nullable(),
    city_denmark: z.string().optional().nullable(),
    city_finland: z.string().optional().nullable(),
    city_germany: z.string().optional().nullable(),
    city_poland: z.string().optional().nullable(),
    city_norway: z.string().optional().nullable(),
    city_sweden: z.string().optional().nullable(),
    excluded: z.array(z.string()),
  })
  .transform((data) => {
    const cities = [
      data.city_denmark,
      data.city_finland,
      data.city_germany,
      data.city_poland,
      data.city_norway,
      data.city_sweden,
    ].filter((city): city is string => Boolean(city))

    // When there are multiple city values, we return null as the filter is invalid.
    if (cities.length > 1) {
      return null
    }

    return {
      country: cities.length ? null : data.country,
      city: cities.length ? cities[0] : null,
      excluded: data.excluded,
    }
  })

export const hotelListingSchema = z.object({
  typename: z
    .literal(BlocksEnums.block.HotelListing)
    .default(BlocksEnums.block.HotelListing),
  hotel_listing: z
    .object({
      heading: z.string().optional(),
      location_filter: locationFilterSchema,
      manual_filter: z
        .object({
          hotels: z.array(z.string()),
        })
        .transform((data) => ({ hotels: data.hotels.filter(Boolean) })),
      content_type: z.enum(["hotel", "restaurant", "meeting"]),
    })
    .transform(({ heading, location_filter, manual_filter, content_type }) => {
      return {
        heading,
        locationFilter: location_filter,
        hotelsToInclude: manual_filter.hotels,
        contentType: content_type,
      }
    }),
})
