import { Event } from './layoutAlgorithm';
import { ResourceLayout, PendingAppointment } from '../components/Schedule/Sidebar';

// Backend Types (Django)
export interface BackendResource {
    id: number;
    name: string;
    description?: string;
    // Add other backend fields if necessary
}

export interface BackendAppointment {
    id: number;
    resource?: number; // Foreign Key ID
    customer: number; // User ID
    service: number; // Service ID
    start_time: string; // ISO 8601
    end_time: string; // ISO 8601
    status: 'PENDING' | 'CONFIRMED' | 'COMPLETED' | 'CANCELLED' | 'NO_SHOW';
    is_paid: boolean;
    // We might need to fetch related data (customer name, service name) 
    // or expect the serializer to expand them. 
    // For now, assuming expanded or separate lookup.
    customer_name?: string;
    service_name?: string;
}

// Adapter Functions

export const adaptResources = (resources: BackendResource[]): { id: number; name: string }[] => {
    return resources.map(r => ({
        id: r.id,
        name: r.name,
    }));
};

export const adaptEvents = (appointments: BackendAppointment[]): Event[] => {
    return appointments
        .filter(apt => apt.resource !== null && apt.resource !== undefined) // Only scheduled events
        .map(apt => ({
            id: apt.id,
            resourceId: apt.resource!,
            title: apt.customer_name || `Customer ${apt.customer}`,
            serviceName: apt.service_name || `Service ${apt.service}`,
            start: new Date(apt.start_time),
            end: new Date(apt.end_time),
            status: apt.status,
            isPaid: apt.is_paid,
        }));
};

export const adaptPending = (appointments: BackendAppointment[]): PendingAppointment[] => {
    return appointments
        .filter(apt => apt.resource === null || apt.resource === undefined) // Only unscheduled
        .map(apt => {
            const start = new Date(apt.start_time);
            const end = new Date(apt.end_time);
            const durationMinutes = (end.getTime() - start.getTime()) / 60000;

            return {
                id: apt.id,
                customerName: apt.customer_name || `Customer ${apt.customer}`,
                serviceName: apt.service_name || `Service ${apt.service}`,
                durationMinutes: Math.round(durationMinutes),
            };
        });
};
