import { z } from "zod"

import { dt } from "@/lib/dt"

const categoriesSchema = z
  .array(
    z
      .object({ category: z.object({ id: z.number(), text: z.string() }) })
      .transform(({ category }) => {
        return {
          id: category.id,
          text: category.text,
        }
      })
  )
  .transform((categories) =>
    categories.filter(
      (category): category is NonNullable<typeof category> => !!category
    )
  )

const departmentsSchema = z
  .array(
    z
      .object({
        department: z.object({
          id: z.number(),
          name: z.string(),
        }),
      })
      .transform(({ department }) => {
        if (!department.id || !department.name) {
          return null
        }
        return {
          id: department.id,
          name: department.name,
        }
      })
  )
  .transform((departments) =>
    departments.filter(
      (department): department is NonNullable<typeof department> => !!department
    )
  )

const locationsSchema = z
  .array(
    z
      .object({
        location: z.object({
          city: z.string().nullish(),
          country: z.string().nullish(),
          place_id: z.string().nullish(),
          country_short: z.string().nullish(),
        }),
      })
      .transform(({ location }) => {
        if (!location.city || !location.country) {
          return null
        }
        return {
          city: location.city,
          country: location.country,
          countryShort: location.country_short ?? null,
          placeId: location.place_id ?? null,
        }
      })
  )
  .transform((locations) =>
    locations.filter(
      (location): location is NonNullable<typeof location> => !!location
    )
  )

const urlsSchema = z
  .object({
    apply: z.string(),
    ad: z.string(),
  })
  .transform(({ ad }) => ad)

export const jobylonItemSchema = z
  .object({
    id: z.number(),
    title: z.string(),
    from_date: z.string().nullish(),
    to_date: z.string().nullish(),
    categories: categoriesSchema,
    departments: departmentsSchema,
    locations: locationsSchema,
    urls: urlsSchema,
  })
  .transform(
    ({
      id,
      from_date,
      to_date,
      title,
      categories,
      departments,
      locations,
      urls,
    }) => {
      const now = dt.utc()
      const fromDate = from_date ? dt(from_date) : null
      const toDate = to_date ? dt(to_date) : null
      // Transformed to string as Dayjs objects cannot be passed to client components
      const toDateAsString = toDate?.toString() ?? null

      return {
        id,
        title,
        isActive:
          fromDate &&
          now.isSameOrAfter(fromDate) &&
          (!toDate || now.isSameOrBefore(toDate)),
        categories,
        departments,
        toDate: toDateAsString,
        locations,
        url: urls,
      }
    }
  )

export const jobylonFeedSchema = z
  .array(jobylonItemSchema)
  .transform((jobs) => jobs.filter((job) => job.isActive))
