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

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 = { ...req.body, organization_id: req.appUser?.organizationId };
        const { data, error } = await supabase
            .from('yield_studies')
            .insert(toSnakeCase(payload))
            .select()
            .single();
        if (error) throw error;
        res.status(201).json(toCamelCase(data));
    } catch (error: unknown) {
        res.status(400).json({ error: (error as any).message });
    }
};

export const updateStudy = async (req: Request, res: Response) => {
    try {
        const { data, error } = await supabase
            .from('yield_studies')
            .update(toSnakeCase(req.body))
            .eq('id', req.params.id)
            .select()
            .single();
        if (error) throw error;
        res.json(toCamelCase(data));
    } catch (error: unknown) {
        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 });
    }
};