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

export interface Driver {
	transporter_key: string;
	line: number;
	driver_name?: string;
	license_number?: string;
	express_line_id?: string;
	ace_id?: string;
	birth_date?: number;
	gender?: string;
	birth_country?: string;
	hazardous_material_auth?: string;
	hazardous_material_state?: string;
	first_name?: string;
	last_name?: string;
	id_key1?: string;
	id_number1?: string;
	id_state1?: string;
	id_country1?: string;
	id_key2?: string;
	id_number2?: string;
	id_state2?: string;
	id_country2?: string;
	badge_number?: string;
	class_type?: string;
	unique_badge_number?: string;
	company_id?: number;
	tenant_id?: number;
}

export interface DriverResponse {
	items: Driver[];
	total: number;
	page: number;
	page_size: number;
}

class DriversApi {
	private baseUrl = '/v1/a76/drivers';

	async list(
		companyId: string | number,
		params?: Record<string, string | number | undefined>
	): Promise<ApiResponse<DriverResponse>> {
		const queryParams = new URLSearchParams({
			company_id: companyId.toString(),
			...(params as Record<string, string>)
		});
		return api.get<DriverResponse>(`${this.baseUrl}?${queryParams.toString()}`);
	}

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

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

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

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

export const driversApi = new DriversApi();
