import { DateTime, Interval } from 'luxon';
import { TimeTrackingDaySummary } from '../models/daySummary';
import { CategoryInput } from '../models/timeTracking/categorizationTrace';

/**
 * Converts Luxon Intervals to [HH:MM, HH:MM] tuples for JSON serialization.
 */
export function intervalsToTuples(intervals: Interval[], timezone: string): [string, string][] {
    return intervals.map((interval) => {
        const start = interval.start!.setZone(timezone);
        const end = interval.end!.setZone(timezone);
        return [start.toFormat('HH:mm'), end.toFormat('HH:mm')];
    });
}

/**
 * Builds the CategoryInput payload from a daySummary and its derived workedIntervals.
 * Emitted once per (user, date, category) in the CATEGORY_ENTER event.
 */
export function buildCategoryInput(daySummary: TimeTrackingDaySummary, workedIntervals: Interval[], timezone: string): CategoryInput {
    const entries = (daySummary.timeTrackingEntries ?? []).map((e) => ({
        entryId: e.id,
        type: e.type,
        time: DateTime.fromJSDate(e.time).setZone(timezone).toFormat('HH:mm'),
    }));

    const timeSlots = (daySummary.timeSlots ?? []).map((slot) => ({
        startTime: slot.startTime,
        endTime: slot.endTime,
    }));

    const holidays = (daySummary.holidays ?? []).map((h) => ({ id: h.holidayId, name: h.holidayName }));

    return {
        dateString: daySummary.dateString,
        isWorkday: daySummary.isWorkday,
        weekday: daySummary.weekday,
        scheduledHours: daySummary.scheduledHours ?? 0,
        scheduleSource: daySummary.scheduleSource,
        nightShift: daySummary.nightShift ?? false,
        holidays,
        timeOffHours: daySummary.timeOffHours ?? null,
        timeSlots,
        entries,
        workedIntervals: intervalsToTuples(workedIntervals, timezone),
    };
}
