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

export interface ManifestDriver {
    manifest_number: string;
    driver_name: string;
    driver_type?: string;
    address_1?: string;
    address_2?: string;
    city?: string;
    state?: string;
    postal_code?: string;
    country?: string;
    company_id?: number;
    tenant_id?: number;
}

export interface ManifestDriverResponse {
    items: ManifestDriver[];
    total: number;
    page: number;
    page_size: number;
}

export type ManifestDriverCreate = Omit<ManifestDriver, 'company_id' | 'tenant_id'>;
export type ManifestDriverUpdate = Partial<ManifestDriverCreate>;

class ManifestDriversApi {
    private baseUrl = '/v1/a76/manifest-drivers';

    async list(
        companyId: string | number,
        manifest_number?: string,
        skip: number = 0,
        limit: number = 100
    ): Promise<ApiResponse<ManifestDriverResponse>> {
        const params = new URLSearchParams({
            company_id: companyId.toString(),
            skip: skip.toString(),
            limit: limit.toString()
        });

        if (manifest_number) {
            params.append('manifest_number', manifest_number);
        }

        return api.get<ManifestDriverResponse>(`${this.baseUrl}?${params.toString()}`);
    }

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

    async update(
        manifestNumber: string,
        driverName: string,
        companyId: string | number,
        data: ManifestDriverUpdate
    ): Promise<ApiResponse<ManifestDriver>> {
        const params = new URLSearchParams({
            company_id: companyId.toString()
        });
        return api.patch<ManifestDriver>(
            `${this.baseUrl}/${manifestNumber}/${driverName}?${params.toString()}`,
            data
        );
    }

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

export const manifestDriversApi = new ManifestDriversApi();
