import moment from "moment";
import type { AppointmentTimes } 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 extractTime(date: Date): string {
    return moment(date).format("HH:mm");
}

export function extractDate(date: Date): string {
    return moment(date).format("DD.MM.YYYY");
}

export function getTimeSlots(startDate: string, startTime: string, endTime: string, intervalMinutes: number = 15): 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
        }

        timeSlots.push({date: start.format('YYYY-MM-DDTHH:mm'), available: true}); // 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;
}