import { Request, Response } from 'express';
import { supabase } from '../config/supabase.js';

export const createInstrument = async (req: Request, res: Response) => {
    try {
        const { data, error } = await supabase
            .from('instruments')
            .insert({ ...req.body, organization_id: req.appUser?.organizationId })
            .select()
            .single();
        if (error) throw error;
        res.status(201).json(data);
    } catch (error: unknown) {
        res.status(500).json({ error: error instanceof Error ? error.message : 'Unknown error' });
    }
};

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

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

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