import { z } from "zod"

import { ChildBedTypeEnum } from "@/constants/booking"

import { phoneValidator } from "@/utils/phoneValidator"

import { CurrencyEnum } from "@/types/enums/currency"

// MUTATION
export const createBookingSchema = z
  .object({
    data: z.object({
      attributes: z.object({
        confirmationNumber: z.string(),
        cancellationNumber: z.string().nullable(),
        reservationStatus: z.string(),
        paymentUrl: z.string().nullable(),
        metadata: z.any(), // TODO: define metadata schema (not sure what it does)
      }),
      type: z.string(),
      id: z.string(),
      links: z.object({
        self: z.object({
          href: z.string().url(),
          meta: z.object({
            method: z.string(),
          }),
        }),
      }),
    }),
  })
  .transform((d) => ({
    id: d.data.id,
    links: d.data.links,
    type: d.data.type,
    confirmationNumber: d.data.attributes.confirmationNumber,
    cancellationNumber: d.data.attributes.cancellationNumber,
    reservationStatus: d.data.attributes.reservationStatus,
    paymentUrl: d.data.attributes.paymentUrl,
  }))

// QUERY
const extraBedTypesSchema = z.object({
  quantity: z.number(),
  bedType: z.nativeEnum(ChildBedTypeEnum),
})

const guestSchema = z.object({
  email: z.string().email().nullable().default(""),
  firstName: z.string(),
  lastName: z.string(),
  phoneNumber: phoneValidator().nullable().default(""),
})

const packageSchema = z.object({
  code: z.string().default(""),
  currency: z.nativeEnum(CurrencyEnum),
  quantity: z.number().int(),
  totalPrice: z.number(),
  totalQuantity: z.number().int(),
  unitPrice: z.number(),
})

export const bookingConfirmationSchema = z
  .object({
    data: z.object({
      attributes: z.object({
        adults: z.number(),
        checkInDate: z.date({ coerce: true }),
        checkOutDate: z.date({ coerce: true }),
        createDateTime: z.date({ coerce: true }),
        childrenAges: z.array(z.number()),
        extraBedTypes: z.array(extraBedTypesSchema).default([]),
        computedReservationStatus: z.string(),
        confirmationNumber: z.string(),
        currencyCode: z.nativeEnum(CurrencyEnum),
        guest: guestSchema,
        hotelId: z.string(),
        packages: z.array(packageSchema),
        rateCode: z.string(),
        reservationStatus: z.string(),
        roomPrice: z.number().int(),
        roomTypeCode: z.string(),
        totalPrice: z.number(),
        totalPriceExVat: z.number(),
        vatAmount: z.number(),
        vatPercentage: z.number(),
      }),
      id: z.string(),
      type: z.literal("booking"),
    }),
  })
  .transform(({ data }) => data.attributes)
