import { z } from "zod";
import { controllerProcedure, protectedProcedure } from "../trpc.js";
import {
  buildSelfServiceTimelineInput,
  createTimelineDateRange,
  createTimelineFilters,
  TimelineWindowFiltersSchema,
} from "./timeline-read-shared.js";
import {
  loadTimelineHolidayOverlays,
} from "./timeline-holiday-load-support.js";
import {
  buildTimelineHolidayOverlayDetailResponse,
  formatTimelineHolidayOverlays,
  summarizeTimelineHolidayOverlays,
  type TimelineHolidayOverlayRecord,
} from "./timeline-holiday-support.js";

export {
  loadTimelineHolidayOverlays,
  loadTimelineHolidayOverlaysForReadModel,
} from "./timeline-holiday-load-support.js";

export function formatHolidayOverlays(
  overlays: TimelineHolidayOverlayRecord[],
) {
  return formatTimelineHolidayOverlays(overlays);
}

export function summarizeHolidayOverlays(
  overlays: ReturnType<typeof formatHolidayOverlays>,
) {
  return summarizeTimelineHolidayOverlays(overlays);
}

export const timelineHolidayReadProcedures = {
  getHolidayOverlays: controllerProcedure
    .input(TimelineWindowFiltersSchema)
    .query(async ({ ctx, input }) => loadTimelineHolidayOverlays(ctx.db, input)),

  getMyHolidayOverlays: protectedProcedure
    .input(TimelineWindowFiltersSchema)
    .query(async ({ ctx, input }) => {
      const selfServiceInput = await buildSelfServiceTimelineInput(ctx, input);
      if (!selfServiceInput) {
        return [];
      }

      return loadTimelineHolidayOverlays(ctx.db, selfServiceInput);
    }),

  getHolidayOverlayDetail: controllerProcedure
    .input(
      z.object({
        startDate: z.string().optional(),
        endDate: z.string().optional(),
        durationDays: z.number().int().min(1).max(366).optional(),
        resourceIds: z.array(z.string()).optional(),
        projectIds: z.array(z.string()).optional(),
        clientIds: z.array(z.string()).optional(),
        chapters: z.array(z.string()).optional(),
        eids: z.array(z.string()).optional(),
        countryCodes: z.array(z.string()).optional(),
      }),
    )
    .query(async ({ ctx, input }) => {
      const { startDate, endDate } = createTimelineDateRange(input);
      const filters = createTimelineFilters(input);
      const holidayOverlays = await loadTimelineHolidayOverlays(ctx.db, {
        ...filters,
        startDate,
        endDate,
      });
      const formattedOverlays = formatHolidayOverlays(holidayOverlays);

      return buildTimelineHolidayOverlayDetailResponse({
        startDate,
        endDate,
        filters,
        overlays: formattedOverlays,
      });
    }),
};
