import { apiClient, ensureCsrfCookie } from './client';

/**
 * Reminders API (schema v8.10 §17.5).
 *
 * Все endpoint'ы под Sanctum SPA auth.
 * Mutating-вызовы (POST/PATCH/DELETE) делают ensureCsrfCookie().
 */

export type ReminderFilter = 'active' | 'today' | 'upcoming' | 'overdue' | 'completed';

export interface ApiReminder {
    id: number;
    deal_id: number;
    text: string | null;
    remind_at: string | null;
    completed_at: string | null;
    is_sent: boolean;
    sent_at: string | null;
    created_at: string | null;
    created_by: number;
    assignee_id: number | null;
    creator_name: string | null;
}

export interface ReminderCounts {
    active: number;
    today: number;
    upcoming: number;
    overdue: number;
}

export interface ListRemindersResponse {
    items: ApiReminder[];
    counts: ReminderCounts;
}

export interface ListRemindersParams {
    filter?: ReminderFilter;
    dealId?: number;
    limit?: number;
}

export async function listReminders(params: ListRemindersParams = {}): Promise<ListRemindersResponse> {
    const { data } = await apiClient.get<ListRemindersResponse>('/api/reminders', {
        params: {
            filter: params.filter,
            deal_id: params.dealId,
            limit: params.limit,
        },
    });
    return data;
}

export interface CreateReminderPayload {
    deal_id: number;
    text?: string | null;
    remind_at: string;
    assignee_id?: number | null;
}

export async function createReminder(payload: CreateReminderPayload): Promise<ApiReminder> {
    await ensureCsrfCookie();
    const { data } = await apiClient.post<{ reminder: ApiReminder }>('/api/reminders', payload);
    return data.reminder;
}

export interface UpdateReminderPayload {
    text?: string | null;
    remind_at?: string;
    assignee_id?: number | null;
}

export async function updateReminder(id: number, payload: UpdateReminderPayload): Promise<ApiReminder> {
    await ensureCsrfCookie();
    const { data } = await apiClient.patch<{ reminder: ApiReminder }>(`/api/reminders/${id}`, payload);
    return data.reminder;
}

export async function completeReminder(id: number): Promise<ApiReminder> {
    await ensureCsrfCookie();
    const { data } = await apiClient.post<{ reminder: ApiReminder }>(`/api/reminders/${id}/complete`);
    return data.reminder;
}

export async function deleteReminder(id: number): Promise<void> {
    await ensureCsrfCookie();
    await apiClient.delete(`/api/reminders/${id}`);
}
