import { 
    Project, Inspection, ApplicationRecord, TechnicalDataSheet, PaintingScheme, 
    Part, Instrument, YieldStudy, GeometryType, StockItem, StockMovement 
} from '../lib/compat.js';


interface BackupData {
    version: string;
    timestamp: string;
    organizationId: string;
    data: {
        projects: any[];
        inspections: any[];
        applicationRecords: any[];
        technicalDataSheets: any[];
        paintingSchemes: any[];
        parts: any[];
        instruments: any[];
        yieldStudies: any[];
        geometryTypes: any[];
        stockItems: any[];
        stockMovements: any[];
    };
}

export const backupService = {
    /**
     * Exporta todos os dados da organização para um objeto JSON
     */
    async exportData(organizationId: string): Promise<BackupData> {
        try {
            const [
                projects,
                inspections,
                applicationRecords,
                technicalDataSheets,
                paintingSchemes,
                parts,
                instruments,
                yieldStudies,
                geometryTypes,
                stockItems,
                stockMovements
            ] = await Promise.all([
                Project.find({ organizationId }),
                Inspection.find({ organizationId }),
                ApplicationRecord.find({ organizationId }),
                TechnicalDataSheet.find({ organizationId }),
                PaintingScheme.find({ organizationId }),
                Part.find({ organizationId }),
                Instrument.find({ organizationId }),
                YieldStudy.find({ organizationId }),
                GeometryType.find({ organizationId }),
                StockItem.find({ organizationId }),
                StockMovement.find({ organizationId })
            ]);

            const backup: BackupData = {
                version: '1.0.0',
                timestamp: new Date().toISOString(),
                organizationId,
                data: {
                    projects,
                    inspections,
                    applicationRecords,
                    technicalDataSheets,
                    paintingSchemes,
                    parts,
                    instruments,
                    yieldStudies,
                    geometryTypes,
                    stockItems,
                    stockMovements
                }
            };

            return backup;
        } catch (error) {
            console.error('Erro ao exportar dados:', error);
            throw new Error('Falha ao criar backup dos dados');
        }
    },

    /**
     * Importa dados de um backup JSON e sobrescreve os dados atuais da organização
     */
    async importData(backupData: BackupData, organizationId: string): Promise<void> {
        try {
            // Validação básica
            if (!backupData.version || !backupData.data) {
                throw new Error('Formato de backup inválido');
            }

            // Verifica se o backup é da mesma organização (segurança adicional)
            if (backupData.organizationId !== organizationId) {
                throw new Error('Este backup pertence a outra organização');
            }

            // Remove todos os dados atuais da organização
            await Promise.all([
                Project.deleteMany({ organizationId }),
                Inspection.deleteMany({ organizationId }),
                ApplicationRecord.deleteMany({ organizationId }),
                TechnicalDataSheet.deleteMany({ organizationId }),
                PaintingScheme.deleteMany({ organizationId }),
                Part.deleteMany({ organizationId }),
                Instrument.deleteMany({ organizationId }),
                YieldStudy.deleteMany({ organizationId }),
                GeometryType.deleteMany({ organizationId }),
                StockItem.deleteMany({ organizationId }),
                StockMovement.deleteMany({ organizationId })
            ]);

            // Insere os dados do backup
            const { data } = backupData;

            await Promise.all([
                data.projects.length > 0 ? Project.insertMany(data.projects) : Promise.resolve(),
                data.inspections.length > 0 ? Inspection.insertMany(data.inspections) : Promise.resolve(),
                data.applicationRecords.length > 0 ? ApplicationRecord.insertMany(data.applicationRecords) : Promise.resolve(),
                data.technicalDataSheets.length > 0 ? TechnicalDataSheet.insertMany(data.technicalDataSheets) : Promise.resolve(),
                data.paintingSchemes.length > 0 ? PaintingScheme.insertMany(data.paintingSchemes) : Promise.resolve(),
                data.parts.length > 0 ? Part.insertMany(data.parts) : Promise.resolve(),
                data.instruments.length > 0 ? Instrument.insertMany(data.instruments) : Promise.resolve(),
                data.yieldStudies.length > 0 ? YieldStudy.insertMany(data.yieldStudies) : Promise.resolve(),
                data.geometryTypes.length > 0 ? GeometryType.insertMany(data.geometryTypes) : Promise.resolve(),
                data.stockItems.length > 0 ? StockItem.insertMany(data.stockItems) : Promise.resolve(),
                data.stockMovements.length > 0 ? StockMovement.insertMany(data.stockMovements) : Promise.resolve()
            ]);

            console.log(`Backup restaurado com sucesso para organização ${organizationId}`);
        } catch (error) {
            console.error('Erro ao importar dados:', error);
            throw new Error('Falha ao restaurar backup');
        }
    },

    /**
     * Retorna estatísticas do backup para exibição
     */
    getBackupStats(backupData: BackupData): Record<string, number> {
        return {
            projects: backupData.data.projects.length,
            inspections: backupData.data.inspections.length,
            applicationRecords: backupData.data.applicationRecords.length,
            technicalDataSheets: backupData.data.technicalDataSheets.length,
            paintingSchemes: backupData.data.paintingSchemes.length,
            parts: backupData.data.parts.length,
            instruments: backupData.data.instruments.length,
            yieldStudies: backupData.data.yieldStudies.length,
            geometryTypes: backupData.data.geometryTypes.length,
            stockItems: backupData.data.stockItems.length,
            stockMovements: backupData.data.stockMovements.length
        };
    }
};
