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

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);

        try { fs.unlinkSync(localPath); } catch {}
        
        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 getFileStream = (fileUrl: string) => {
    return fileUrl;
};

export const getAllDataSheets = async (organizationId?: string) => {
    try {
        let query = supabase.from('technical_data_sheets').select('*');
        if (organizationId) {
            query = query.eq('organization_id', organizationId);
        }
        const { data, error } = await query;
        if (error && error.code !== '42P01') throw error;
        return data || [];
    } catch (err) {
        console.log('Error fetching datasheets:', err);
        return [];
    }
};

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) => {
    return getAllDataSheets(organizationId);
};

export const createDataSheet = async (data: any) => {
    const { data: sheet, error } = await supabase
        .from('technical_data_sheets')
        .insert(data)
        .select()
        .single();

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

export const updateDataSheet = async (id: string, data: any, organizationId?: string) => {
    const { data: sheet, error } = await supabase
        .from('technical_data_sheets')
        .update(data)
        .eq('id', id)
        .select()
        .single();

    if (error && error.code !== '42P01') throw error;
    return sheet;
};

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

    if (error && error.code !== '42P01') throw error;
    return true;
};

