import { Request, Response } from 'express';
import { supabase } from '../config/supabase.js';
import { toCamelCase, toSnakeCase } from '../utils/caseMapper.js';

const sanitizeStudyPayload = (body: any) => {
    const payload = { ...body };

    if (payload.dataSheetId && typeof payload.dataSheetId === 'object') {
        payload.dataSheetId = payload.dataSheetId.id || payload.dataSheetId._id || payload.dataSheetId;
    }
    if (payload.data_sheet_id && typeof payload.data_sheet_id === 'object') {
        payload.data_sheet_id = payload.data_sheet_id.id || payload.data_sheet_id._id || payload.data_sheet_id;
    }

    delete payload.id;
    delete payload._id;
    delete payload.createdAt;
    delete payload.created_at;
    delete payload.updatedAt;
    delete payload.updated_at;
    delete payload.calculatedEpu;
    delete payload.calculated_epu;

    return toSnakeCase(payload);
};

export const getAllStudies = async (req: Request, res: Response) => {
    try {
        const { data, error } = await supabase.from('yield_studies').select('*');
        if (error && error.code !== '42P01') throw error;
        res.json(toCamelCase(data || []));
    } catch (error: unknown) {
        res.json([]);
    }
};

export const createStudy = async (req: Request, res: Response) => {
    try {
        const payload = sanitizeStudyPayload({ ...req.body, organization_id: req.appUser?.organizationId });
        const { data, error } = await supabase
            .from('yield_studies')
            .insert(payload)
            .select()
            .single();
        if (error) throw error;
        res.status(201).json(toCamelCase(data));
    } catch (error: unknown) {
        console.error('Error creating study:', error);
        res.status(400).json({ error: (error as any).message });
    }
};

export const updateStudy = async (req: Request, res: Response) => {
    try {
        const payload = sanitizeStudyPayload(req.body);
        const { data, error } = await supabase
            .from('yield_studies')
            .update(payload)
            .eq('id', req.params.id)
            .select()
            .single();
        if (error) throw error;
        res.json(toCamelCase(data));
    } catch (error: unknown) {
        console.error('Error updating study:', error);
        res.status(400).json({ error: (error as any).message });
    }
};

export const deleteStudy = async (req: Request, res: Response) => {
    try {
        await supabase.from('yield_studies').delete().eq('id', req.params.id);
        res.status(204).send();
    } catch (error: unknown) {
        res.status(500).json({ error: (error as any).message });
    }
};