import { api } from '$lib/api';
import type { ApiResponse } from '$lib/api';

export interface Signature {
    id: number;
	
    code: string;               
    signature: string | null;   
    photo_path: string | null; 
    
   
    tenant_id: number;
    company_id: number;
    created_at: string;
    updated_at?: string;
}

export interface SignatureCreate {
    code: string;
    signature?: string | null;
    photo_path?: string | null;
   
}

export interface SignatureUpdate extends Partial<SignatureCreate> {}

export interface SignatureListResponse {
    items: Signature[];
    total: number;
    page: number;
    page_size: number;
    pages: number;
}


export async function getSignatures(
    page: number = 1,
    pageSize: number = 50,
    companyId: number, 
    filters: Record<string, any> = {}
): Promise<ApiResponse<SignatureListResponse>> {
    const params = new URLSearchParams({
        page: page.toString(),
        page_size: pageSize.toString(),
        company_id: companyId.toString(),
        ...filters
    });


    const response = await api.get(`/v1/a76/signatures/?${params.toString()}`);
    return response.data;
}


export async function getSignature(id: number, companyId: number): Promise<Signature> {
    const response = await api.get(`/v1/a76/signatures/${id}?company_id=${companyId}`);
    if (response.error) throw new Error(response.error);
    return response.data;
}


export async function createSignature(
    data: SignatureCreate, 
    companyId: number
): Promise<Signature> {
    const response = await api.post(`/v1/a76/signatures/?company_id=${companyId}`, data);
    if (response.error) throw new Error(response.error);
    return response.data;
}

export async function updateSignature(
    id: number, 
    data: SignatureUpdate, 
    companyId: number
): Promise<Signature> {
    const response = await api.put(`/v1/a76/signatures/${id}/?company_id=${companyId}`, data);
    if (response.error) throw new Error(response.error);
    return response.data;
}

export async function deleteSignature(id: number, companyId: number): Promise<void> {
    const response = await api.delete(`/v1/a76/signatures/${id}?company_id=${companyId}`);
    if (response.error) throw new Error(response.error);
}

export const signaturesApi = {
    list: (companyId: number, options: Record<string, any> = {}) => {
        const { page = '1', page_size = '50', ...filters } = options;
        return getSignatures(Number(page), Number(page_size), companyId, filters);
    },
    get: (id: number, companyId: number) => getSignature(id, companyId),
    create: (data: SignatureCreate, companyId: number) => createSignature(data, companyId),
    update: (id: number, data: SignatureUpdate, companyId: number) => updateSignature(id, data, companyId),
    delete: (id: number, companyId: number) => deleteSignature(id, companyId)
};