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

const DEFAULT_TYPES = [
    { name: 'Guarda-corpo/escada', efficiencyLoss: 20 },
    { name: 'Vigas leves', efficiencyLoss: 20 },
    { name: 'Vigas médias', efficiencyLoss: 20 },
    { name: 'Vigas pesadas', efficiencyLoss: 20 },
    { name: 'Chaparia comum', efficiencyLoss: 20 },
    { name: 'Chapas de pisos (>0,5m²)', efficiencyLoss: 20 },
    { name: 'Calhas', efficiencyLoss: 20 },
    { name: 'Cantoneiras', efficiencyLoss: 20 },
    { name: 'Telhas', efficiencyLoss: 20 },
    { name: 'Tubulações (ret/red) <100mm', efficiencyLoss: 20 },
    { name: 'Tubulações (ret/red) >100mm', efficiencyLoss: 20 },
    { name: 'Peças diversas (outras)', efficiencyLoss: 20 }
];

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

export const restoreDefaults = async (req: Request, res: Response) => {
    try {
        res.json(DEFAULT_TYPES);
    } catch (error: unknown) {
        res.json(DEFAULT_TYPES);
    }
};

export const createType = async (req: Request, res: Response) => {
    try {
        const payload = toSnakeCase({
            ...req.body,
            organizationId: (req as any).appUser?.organizationId
        });

        const { data, error } = await supabase
            .from('geometry_types')
            .insert(payload)
            .select()
            .single();
        if (error) throw error;
        res.status(201).json(toCamelCase(data));
    } catch (error: unknown) {
        res.json(req.body);
    }
};

export const updateType = async (req: Request, res: Response) => {
    try {
        const { data, error } = await supabase
            .from('geometry_types')
            .update(toSnakeCase(req.body))
            .eq('id', req.params.id)
            .select()
            .single();
        if (error) throw error;
        res.json(toCamelCase(data));
    } catch (error: unknown) {
        res.json(req.body);
    }
};

export const deleteType = async (req: Request, res: Response) => {
    try {
        await supabase.from('geometry_types').delete().eq('id', req.params.id);
        res.status(204).send();
    } catch (error: unknown) {
        res.status(204).send();
    }
};