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

export interface Concept {
    id: number;
    code: string;
    description?: string;
    description_en?: string;
    detailed_description?: string;
    priority?: number;
    priority_ame?: number;
    first_total?: boolean;
    type?: string;
    is_printed?: boolean;
    section?: number;
    classification?: string;
    tenant_id: string;
    company_id?: string;
    created_at: string;
    updated_at?: string;
}

export interface ConceptCreate {
    code: string;
    description?: string;
    description_en?: string;
    detailed_description?: string;
    priority?: number;
    priority_ame?: number;
    first_total?: boolean;
    type?: string;
    is_printed?: boolean;
    section?: number;
    classification?: string;
}

export interface ConceptUpdate extends Partial<ConceptCreate> {}

export interface ConceptListResponse {
    items: Concept[];
    total: number;
    page: number;
    page_size: number;
    pages: number;
}

export async function getConcepts(
    page: number = 1,
    pageSize: number = 50,
    companyId: number, 
    filters: Record<string, any> = {}, 
): Promise<ApiResponse<ConceptListResponse>> {
    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 params = new URLSearchParams({
        page: page.toString(),
        page_size: pageSize.toString(),
        company_id: companyId.toString(), 
        ...cleanFilters
    });

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


export async function getConcept(id: number, companyId: number): Promise<ApiResponse<Concept>> {
    return await api.get(`/v1/a76/concepts/${id}?company_id=${companyId}`);
}


export async function createConcept(data: ConceptCreate, companyId: number): Promise<ApiResponse<Concept>> {
    return await api.post(`/v1/a76/concepts/?company_id=${companyId}`, data);
}


export async function updateConcept(id: number, data: ConceptUpdate, companyId: number): Promise<ApiResponse<Concept>> {
    return await api.put(`/v1/a76/concepts/${id}/?company_id=${companyId}`, data);
}


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