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

export interface Identifier {
    id: number;
    code: string;
    description: string | null;
    level: string | null;
    complement: string | null;
    company_id: number; 
    tenant_id: number;  
    created_at: string | null;
    updated_at: string | null;
}

export interface IdentifierCreate {
    code: string;
    description?: string | null;
    level?: string | null;
    complement?: string | null;
}

export interface IdentifierUpdate {
    code?: string;
    description?: string | null;
    level?: string | null;
    complement?: string | null;
}

export interface IdentifierListResponse {
    items: Identifier[];
    total: number;
    page: number;
    page_size: number;
    pages: number;
}

export interface IdentifierDetail {
    id: number;
    invoice_consecutive: number | null;
    part_line: number | null;
    identifier_code: string | null;
    module: string | null;
    complement1: string | null;
    complement2: string | null;
    complement3: string | null;
    item_line_id: number | null;
    company_id: number;
    tenant_id: number;
}

export interface IdentifierDetailCreate {
    invoice_consecutive?: number | null;
    part_line?: number | null;
    identifier_code?: string | null;
    module?: string | null;
    complement1?: string | null;
    complement2?: string | null;
    complement3?: string | null;
    item_line_id?: number | null;
}

export interface IdentifierDetailUpdate extends Partial<IdentifierDetailCreate> { }

export async function getIdentifiers(
    page = 1,
    pageSize = 50,
    companyId: number, 
    filters: Record<string, any> = {}
): Promise<ApiResponse<IdentifierListResponse>> {
    const cleanFilters = Object.fromEntries(
        Object.entries(filters).filter(([, value]) => {
            if (value === undefined || value === null) return false;
            if (typeof value === 'string') {
                const trimmed = value.trim();
                return trimmed !== '' && trimmed.toLowerCase() !== 'undefined';
            }
            return true;
        })
    );

    const queryParams = new URLSearchParams({
        page: page.toString(),
        page_size: pageSize.toString(),
        company_id: companyId.toString(), 
        ...cleanFilters
    });

    return await api.get(`/v1/a76/identifiers/?${queryParams.toString()}`);
}

export async function createIdentifier(
    data: IdentifierCreate, 
    companyId: number
): Promise<ApiResponse<Identifier>> {
    return await api.post(`/v1/a76/identifiers/?company_id=${companyId}`, data);
}

export async function updateIdentifier(
    id: number, 
    data: IdentifierUpdate, 
    companyId: number
): Promise<ApiResponse<Identifier>> {
    return await api.put(`/v1/a76/identifiers/${id}/?company_id=${companyId}`, data);
}

export async function deleteIdentifier(
    id: number, 
    companyId: number
): Promise<ApiResponse<void>> {
    return await api.delete(`/v1/a76/identifiers/${id}?company_id=${companyId}`);
}

/**
 * API for Identifier Details
 */
export async function createIdentifierDetail(
    data: IdentifierDetailCreate,
    companyId: number
): Promise<ApiResponse<IdentifierDetail>> {
    return await api.post(`/v1/a76/identifiers/details/?company_id=${companyId}`, data);
}

export async function updateIdentifierDetail(
    id: number,
    data: IdentifierDetailUpdate,
    companyId: number
): Promise<ApiResponse<IdentifierDetail>> {
    return await api.put(`/v1/a76/identifiers/details/${id}/?company_id=${companyId}`, data);
}

export async function deleteIdentifierDetail(
    id: number,
    companyId: number
): Promise<ApiResponse<void>> {
    return await api.delete(`/v1/a76/identifiers/details/${id}?company_id=${companyId}`);
}

export const identifiersApi = {
    list: (companyId: number, options: Record<string, any> = {}) => {
        const { page = '1', page_size = '50', ...filters } = options;
        return getIdentifiers(Number(page), Number(page_size), companyId, filters);
    },
    get: (id: number, companyId: number) => {
        return api.get(`/v1/a76/identifiers/${id}?company_id=${companyId}`);
    },
    create: (data: IdentifierCreate, companyId: number) => createIdentifier(data, companyId),
    update: (id: number, data: IdentifierUpdate, companyId: number) => updateIdentifier(id, data, companyId),
    delete: (id: number, companyId: number) => deleteIdentifier(id, companyId),
    // Details
    createDetail: (data: IdentifierDetailCreate, companyId: number) => createIdentifierDetail(data, companyId),
    updateDetail: (id: number, data: IdentifierDetailUpdate, companyId: number) => updateIdentifierDetail(id, data, companyId),
    deleteDetail: (id: number, companyId: number) => deleteIdentifierDetail(id, companyId)
};