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

export interface Transporter {
    transporter_key: string;
    transporter_id?: number;
    name?: string;
    short_name?: string;
    responsible?: string;
    rfc?: string;
    streets?: string;
    postal_code?: string;
    city?: string;
    state?: string;
    country?: string;
    loader_code?: string;
    caat_code?: string;
    transport_code?: string;
    transport_interface_type?: string;
    ftp_server?: string;
    ftp_user?: string;
    ftp_password?: string;
    ftp_directory?: string;
    filler_code?: string;
    has_express_line?: boolean;
    company_id?: number | string;
    tenant_id?: number | string;
}

export interface TransporterResponse {
    items: Transporter[];
    total: number;
    page: number;
    page_size: number;
}

class TransportersApi {
    private baseUrl = '/v1/a76/transporters';

	async list(
		companyId: string | number,
		params?: Record<string, string | number | undefined>
	): Promise<ApiResponse<TransporterResponse>> {
		const raw: Record<string, string | number> = {
			company_id: companyId.toString(),
			...params
		};
		const queryParams = new URLSearchParams();
		for (const [k, v] of Object.entries(raw)) {
			if (v != null && v !== '') {
				queryParams.set(k, String(v));
			}
		}
		return api.get<TransporterResponse>(`${this.baseUrl}?${queryParams.toString()}`);
	}

    async get(id: string, companyId: string | number): Promise<ApiResponse<Transporter>> {
        const queryParams = new URLSearchParams({
            company_id: companyId.toString()
        });
        return api.get<Transporter>(`${this.baseUrl}/${id}?${queryParams.toString()}`);
    }

    async create(data: Transporter, companyId: string | number): Promise<ApiResponse<Transporter>> {
        const queryParams = new URLSearchParams({
            company_id: companyId.toString()
        });
        return api.post<Transporter>(`${this.baseUrl}?${queryParams.toString()}`, data);
    }

    async update(id: string, data: Transporter, companyId: string | number): Promise<ApiResponse<Transporter>> {
        const queryParams = new URLSearchParams({
            company_id: companyId.toString()
        });
        return api.put<Transporter>(`${this.baseUrl}/${id}/?${queryParams.toString()}`, data);
    }

    async delete(id: string, companyId: string | number): Promise<ApiResponse<void>> {
        const queryParams = new URLSearchParams({
            company_id: companyId.toString()
        });
        return api.delete<void>(`${this.baseUrl}/${id}?${queryParams.toString()}`);
    }
}

export const transportersApi = new TransportersApi();
