import TechnicalDataSheet from '../models/TechnicalDataSheet.js';
import fs from 'fs';
import path from 'path';
import { supabase } from '../config/supabase.js';

const BUCKET_NAME = 'gpi-files';

export const saveFileToStorage = async (localPath: string, filename: string): Promise<string> => {
    try {
        const fileBuffer = fs.readFileSync(localPath);
        const fileExt = path.extname(filename);
        const uniqueName = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}${fileExt}`;
        
        const { data, error } = await supabase.storage
            .from(BUCKET_NAME)
            .upload(uniqueName, fileBuffer, {
                contentType: getContentType(fileExt)
            });

        if (error) throw error;

        const { data: urlData } = supabase.storage
            .from(BUCKET_NAME)
            .getPublicUrl(uniqueName);

        fs.unlinkSync(localPath);
        
        return urlData.publicUrl;
    } catch (err) {
        console.error('Failed to upload file:', err);
        throw err;
    }
};

export const deleteFileFromStorage = async (fileUrl: string): Promise<boolean> => {
    try {
        const fileName = fileUrl.split('/').pop();
        if (!fileName) return false;
        
        const { error } = await supabase.storage
            .from(BUCKET_NAME)
            .remove([fileName]);

        if (error) throw error;
        return true;
    } catch (err) {
        console.error('Failed to delete file:', err);
        return false;
    }
};

function getContentType(ext: string): string {
    const types: Record<string, string> = {
        '.pdf': 'application/pdf',
        '.jpg': 'image/jpeg',
        '.jpeg': 'image/jpeg',
        '.png': 'image/png',
        '.doc': 'application/msword',
        '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    };
    return types[ext.toLowerCase()] || 'application/octet-stream';
}

export const saveFileToGridFS = saveFileToStorage;
export const deleteFileFromGridFS = deleteFileFromStorage;

export const getFileStream = (fileUrl: string) => {
    return fileUrl;
};

export const migrateFilesToGridFS = async () => {
    console.log('ℹ️ File migration skipped - using Supabase Storage');
};

export const uploadDataSheetFile = async (file: any, organizationId: string) => {
    const { data, error } = await supabase
        .from('technical_data_sheets')
        .insert({
            organization_id: organizationId,
            name: file.originalname,
            file_url: file.path
        })
        .select()
        .single();

    if (error) throw error;
    return data;
};

export const getDataSheets = async (organizationId: string) => {
    const { data, error } = await supabase
        .from('technical_data_sheets')
        .select('*')
        .eq('organization_id', organizationId);

    if (error) throw error;
    return data || [];
};

export const deleteDataSheet = async (id: string) => {
    const { error } = await supabase
        .from('technical_data_sheets')
        .delete()
        .eq('id', id);

    if (error) throw error;
};

console.log('✅ DataSheetService loaded with Supabase Storage');
