/**
 * API Client para Reportes de Movimientos de Facturas
 */
import { api } from '$lib/api';

// ===== TYPES =====

export type RangeType = 'FF' | 'FP'; // FF = fecha factura, FP = fecha pago
export type ReportType = 'Normal' | 'Detallado';
export type CurrencyType = 'ME' | 'MN'; // ME = moneda extranjera, MN = moneda nacional
export type ExchangeRateType = 'FP' | 'FF';
export type MovementTypeFilter = 'COMEX' | 'IMPDF' | 'ALL';
export type DischargeFilter = 'SiDes' | 'NoDes' | 'ALL';
export type ExportMovementType = 'AFIJO' | 'NODES' | 'SCRAP' | 'REEXP' | 'DONAC' | 'VEMEX' | 'ALL';

export interface BaseFilter {
	range_type: RangeType;
	start_date: string; // YYYYMMDD format
	end_date: string; // YYYYMMDD format
	include_cancelled: boolean;
	provider?: string | null;
	buyer?: string | null;
	pedimento_code?: string | null;
	report_type: ReportType;
	currency_type: CurrencyType;
	exchange_rate_type: ExchangeRateType;
	is_shelter: boolean;
	database_name: string;
}

export interface ImportTemporaryFilter extends BaseFilter { }

export interface ImportDefinitiveFilter extends BaseFilter {
	movement_type: MovementTypeFilter;
}

export interface ImportRepairFilter extends BaseFilter {
	discharge_filter: DischargeFilter;
}

export interface ExportFilter extends BaseFilter {
	movement_type: ExportMovementType;
	discharge_filter: DischargeFilter;
	use_transport_method: boolean;
}

export interface ExportRepairFilter extends Omit<BaseFilter, 'use_transport_method'> {
	movement_type: ExportMovementType;
	discharge_filter: DischargeFilter;
}

export interface AllMovementsFilter {
	range_type: RangeType;
	start_date: string; // YYYYMMDD format
	end_date: string; // YYYYMMDD format
	include_cancelled: boolean;
	provider?: string | null;
	buyer?: string | null;
	pedimento_code?: string | null;
	report_type: ReportType;
	currency_type: CurrencyType;
	exchange_rate_type: ExchangeRateType;
	is_shelter: boolean;
	operation_type?: 'imp' | 'exp' | null;
	send_email?: boolean;
	// Granular flags
	import_temp?: boolean;
	import_def?: boolean;
	import_rep?: boolean;
	export_def?: boolean;
	export_rep?: boolean;
	export_types?: string[];
	discharge_filter?: DischargeFilter;
}

export interface MovementItem {
	Factura: string;
	Pedimento: string;
	FechaFactura: string | null;
	Estatus: string;
	ClavePed: string;
	TipoMovTemDef: string;
	EsCambioRegimen: string;
	ValorMPTemp: number;
	ValorComercialMN: number;
	TipoCambio: number;
	ValorAgre: number;
	TipoExpo: string;
	PedimentoR1: string | null;
	EDocument: string | null;
	NumOperacionVU: string | null;
	BaseDeDatos: string;
	NumGafUni: string | null;
	UsuarioCap: string | null;
	UsuarioAcr: string | null;
	Fecha_Pago: string | null;
	NumCaja: string | null;
	Pedimento18: string | null;
	AduanaCru: string | null;
	Lote: string | null;
}

export interface MovementItemDetailed extends MovementItem {
	Linea: number;
	Regimen: string | null;
	Fecha_Inicio: string | null;
	Fecha_Fin: string | null;
	Remesa: string | null;
	Proveedor: string | null;
	RFCProveedor: string | null;
	ProveedorTaxID: string | null;
	VendidoA: string | null;
	VendidoARFC: string | null;
	VendidoATaxID: string | null;
	AgenteAduanal: string | null;
	Patente: string | null;
	NumParte: string | null;
	DescripcionE: string | null;
	DescripcionI: string | null;
	CantidadIE: number;
	UniMed: string | null;
	PesoNeto: number;
	PesoBruto: number;
	OrdenCompraVenta: string | null;
	FraccionArancelaria: string | null;
	Preferencia: string | null;
	Sector: string | null;
	PaisOrigen: string | null;
	Aduana: string | null;
	Advalorem: string | null;
	Series: string | null;
	Marca: string | null;
	Modelo: string | null;
	FraccionAmericana: string | null;
	ECCN: string | null;
	SimboloEx: string | null;
	FechaEmision: string | null;
	Transportista: string | null;
}

// ===== API METHODS =====

export const invoiceMovementsApi = {
	// Temporary Imports
	getTemporaryImports: (companyId: number, filters: ImportTemporaryFilter) =>
		api.post<MovementItem[]>(`/v1/a76/reports/movements/invoices/temporary?company_id=${companyId}`, filters),

	getTemporaryImportsDetailed: (companyId: number, filters: ImportTemporaryFilter) =>
		api.post<MovementItemDetailed[]>(
			`/v1/a76/reports/movements/invoices/temporary-detailed?company_id=${companyId}`,
			filters
		),

	// Definitive Imports
	getDefinitiveImports: (companyId: number, filters: ImportDefinitiveFilter) =>
		api.post<MovementItem[]>(`/v1/a76/reports/movements/invoices/definitive?company_id=${companyId}`, filters),

	getDefinitiveImportsDetailed: (companyId: number, filters: ImportDefinitiveFilter) =>
		api.post<MovementItemDetailed[]>(
			`/v1/a76/reports/movements/invoices/definitive-detailed?company_id=${companyId}`,
			filters
		),

	// Repair Imports
	getRepairImports: (companyId: number, filters: ImportRepairFilter) =>
		api.post<MovementItem[]>(`/v1/a76/reports/movements/invoices/repair?company_id=${companyId}`, filters),

	getRepairImportsDetailed: (companyId: number, filters: ImportRepairFilter) =>
		api.post<MovementItemDetailed[]>(
			`/v1/a76/reports/movements/invoices/repair-detailed?company_id=${companyId}`,
			filters
		),

	// Exports
	getExports: (companyId: number, filters: ExportFilter) =>
		api.post<MovementItem[]>(`/v1/a76/reports/movements/invoices/export?company_id=${companyId}`, filters),

	getExportsDetailed: (companyId: number, filters: ExportFilter) =>
		api.post<MovementItemDetailed[]>(`/v1/a76/reports/movements/invoices/export-detailed?company_id=${companyId}`, filters),

	// Export Repairs
	getExportRepairs: (companyId: number, filters: ExportRepairFilter) =>
		api.post<MovementItem[]>(`/v1/a76/reports/movements/invoices/export-repair?company_id=${companyId}`, filters),

	getExportRepairsDetailed: (companyId: number, filters: ExportRepairFilter) =>
		api.post<MovementItemDetailed[]>(
			`/v1/a76/reports/movements/invoices/export-repair-detailed?company_id=${companyId}`,
			filters
		),

	// All Movements
	getAllMovements: (companyId: number, filters: AllMovementsFilter) =>
		api.post<MovementItem[]>(`/v1/a76/reports/movements/invoices/all?company_id=${companyId}`, filters),

	// Async Generation
	generateReportAsync: (companyId: number, filters: AllMovementsFilter) =>
		api.post<{ task_id: string }>(`/v1/a76/reports/movements/invoices/generate?company_id=${companyId}`, filters),

	getTaskStatus: (taskId: string) =>
		api.get<{ task_id: string; status: string; result?: any; meta?: any }>(
			`/v1/a76/reports/movements/invoices/task/${taskId}`
		)
};
