import moment from "moment";
import type { AppointmentDateTimes, AppointmentTimes, WeekSelection } from "./dbdata";
import { goto } from "$app/navigation";

export function isSameDate(dateA: Date, dateB: Date) {
    const date1 = moment(dateA).format('YYYY-MM-DD');
    const date2 = moment(dateB).format('YYYY-MM-DD');

    return date1 === date2;
}

export function getDateString(date: Date): string {
    return moment(date).format('YYYY-MM-DD');
}

export function extractTime(date: Date): string {
    return date.toLocaleTimeString();
}

export function extractDate(date: Date): string {
    return date.toLocaleDateString();
}

export function getTimeSlots(startDate: string, startTime: string, endTime: string, intervalMinutes: number = 15, appointmentTimes: AppointmentDateTimes[] = []): AppointmentTimes[] {
    let start = moment(`${startDate} ${startTime}`, "YYYY-MM-DD HH:mm");
    let end = moment(`${startDate} ${endTime}`, "YYYY-MM-DD HH:mm");
    let timeSlots: AppointmentTimes[] = [];

    while (start <= end) {
        if (start.clone().add(intervalMinutes, "minutes").isAfter(end)) {
            break; // Ensures the last slot does not exceed end time
        }

        // check if the appointment time is already booked
        // to avoid double booking
        const ix: number = appointmentTimes.findIndex(element => moment(element.date).toISOString() === start.toISOString() && element.available === false);
        const isAvailable: boolean = ix === -1;

        timeSlots.push({date: start.format('YYYY-MM-DDTHH:mm'), available: isAvailable}); // ISO-like format
        start.add(intervalMinutes, "minutes");
    }

    return timeSlots;
}

export function toLocalDTSTAMP(date: moment.Moment): string {
    return date.format("YYYYMMDDTHHmmss") + "Z";
}

export function isDueDatePassed(dueDate: Date) {
    return moment(dueDate).isBefore();
}

export async function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
    const response = await fetch(input, init);
    if (response.status === 401) {
        goto("/auth");
        throw new Error("Unauthorized");
    }
    return response;
}

export function generateDateArray(weeks: number): WeekSelection[] {
    const result: WeekSelection[] = [];
    
    // Get the start of the current week
    let currentDate = moment().startOf("isoWeek");

    for (let i = 0; i < weeks; i++) {
        result.push({
            yearWeek: parseInt(currentDate.format("YYYYWW"), 10),
            week: parseInt(currentDate.format("WW"), 10),
            start: currentDate.toDate(),
            end: currentDate.endOf("isoWeek").toDate()
        });
        currentDate.add(1, "week"); // Move to the next week
    }

    return result;
}