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

export interface DownloadedPartsReportSection {
	id: string;
	title: string;
	description: string;
}

export interface DownloadedPartsReportBootstrap {
	report_key: string;
	title: string;
	description: string;
	company_id: number;
	tenant_id: number;
	status: string;
	available_filters: string[];
	next_steps: string[];
	sections: DownloadedPartsReportSection[];
}

export interface DownloadedPartsReportRequest {
	date_from: string;
	date_to: string;
	class_from?: string;
	class_to?: string;
	print_class_mode: 'exported' | 'downloaded';
	exchange_rate_mode: 'invoice' | 'pedimento_payment';
	currency_mode: 'dollars' | 'pesos' | 'both';
	temporality_mode: 'temporales' | 'definitivos' | 'ambos';
	weight_type_mode: 'kilos' | 'libras' | 'ambos';
	operation_mode: 'importacion' | 'exportacion';
	material_type?: string;
	invoice_type?: string;
	parts?: string[];
	pedimento_key?: string;
	provider_id?: number;
	sold_to_id?: number;
	shipped_to_id?: number;
	destination_customs?: string;
	include_series: boolean;
	print_class_total: boolean;
	include_totals_by_fraction: boolean;
	julian_date: boolean;
	show_item_description: boolean;
	include_exempt_fraction: boolean;
	show_export_fraction: boolean;
	include_rule_octava: boolean;
	include_american_fraction_and_country: boolean;
	respect_import_invoice_value_in_pesos: boolean;
	show_all_temporary_balances: boolean;
}

export const downloadedPartsReportsApi = {
	getBootstrap: (companyId: number) =>
		api.get<DownloadedPartsReportBootstrap>(
			`/v1/a76/reports/exportacion/partes-descargadas/bootstrap?company_id=${companyId}`
		),

	generate: async (
		companyId: number,
		params: DownloadedPartsReportRequest
	): Promise<void> => {
		const blob = await api.postBlob(
			`/v1/a76/reports/exportacion/partes-descargadas/generate?company_id=${companyId}`,
			params
		);
		const url = URL.createObjectURL(blob);
		const a = document.createElement('a');
		a.href = url;
		a.download = `partes_descargadas_${params.date_from}_${params.date_to}.csv`;
		document.body.appendChild(a);
		a.click();
		a.remove();
		URL.revokeObjectURL(url);
	}
};
