import { supabase, findOneGpi, queryGpi, insertGpi, updateGpi, deleteGpi } from '../config/supabase.js';

function createModel(tableName: string) {
    return {
        find: async (query: any = {}) => {
            const { data, error } = await queryGpi(tableName, { filter: query });
            if (error) throw error;
            return data || [];
        },
        findOne: async (query: any) => {
            return await findOneGpi(tableName, query);
        },
        findById: async (id: string) => {
            return await findOneGpi(tableName, { id });
        },
        create: async (data: any) => {
            const result = await insertGpi(tableName, data);
            return result.data?.[0] || result.data;
        },
        save: async function() { return this; },
        findOneAndUpdate: async (query: any, update: any) => {
            const existing = await findOneGpi(tableName, query);
            if (!existing) return null;
            const result = await updateGpi(tableName, existing.id, update);
            return result.data?.[0];
        },
        findByIdAndUpdate: async (id: string, update: any) => {
            const result = await updateGpi(tableName, id, update);
            return result.data?.[0];
        },
        findOneAndDelete: async (query: any) => {
            const existing = await findOneGpi(tableName, query);
            if (!existing) return null;
            await deleteGpi(tableName, existing.id);
            return existing;
        },
        findByIdAndDelete: async (id: string) => {
            await deleteGpi(tableName, id);
            return { id };
        },
        aggregate: (pipeline: any[]) => ({ toArray: async () => [] })
    };
}

export const Project = createModel('projects');
export const Part = createModel('parts');
export const PaintingScheme = createModel('painting_schemes');
export const ApplicationRecord = createModel('application_records');
export const Inspection = createModel('inspections');
export const User = createModel('users');
export const Organization = createModel('organizations');
export const OrganizationMember = createModel('user_organizations');
export const StockItem = createModel('stock_items');
export const StockMovement = createModel('stock_movements');
export const StockAuditLog = createModel('stock_audit_logs');
export const Instrument = createModel('instruments');
export const TechnicalDataSheet = createModel('technical_data_sheets');
export const SystemSettings = createModel('system_settings');
export const Notification = createModel('notifications');
export const Message = createModel('messages');
export const GeometryType = createModel('geometry_types');
export const YieldStudy = createModel('yield_studies');
export const StoredFile = createModel('stored_files');

export { queryGpi, findOneGpi, insertGpi, updateGpi, deleteGpi };

console.log('✅ Mongoose Compatibility Layer loaded');
