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

interface AuthRequest extends Request {
    appUser?: IAppUser;
}

export const getStockItems = async (req: AuthRequest, res: Response) => {
    try {
        const { data: items, error: itemsError } = await supabase.from('stock_items').select('*');
        if (itemsError && itemsError.code !== '42P01') throw itemsError;
        if (!items || items.length === 0) return res.json([]);

        // Get unique data sheet IDs
        const dsIds = [...new Set(items.map(i => i.data_sheet_id).filter(Boolean))];
        
        let dataSheets: any[] = [];
        if (dsIds.length > 0) {
            const { data: sheets, error: dsError } = await supabase
                .from('technical_data_sheets')
                .select('*')
                .in('id', dsIds);
            if (!dsError) dataSheets = sheets || [];
        }

        // Map data sheets to a lookup object
        const dsMap = Object.fromEntries(dataSheets.map(ds => [ds.id, ds]));

        // Merge and convert to camelCase
        const enrichedItems = items.map(item => ({
            ...item,
            data_sheet_id: dsMap[item.data_sheet_id] || item.data_sheet_id
        }));

        res.json(toCamelCase(enrichedItems));
    } catch (error: unknown) {
        console.error('Error fetching stock items:', error);
        res.json([]);
    }
};

export const getStockItemById = async (req: AuthRequest, res: Response) => {
    try {
        const { data, error } = await supabase.from('stock_items').select('*').eq('id', req.params.id).single();
        if (error) throw error;
        res.json(toCamelCase(data));
    } catch (error: unknown) {
        res.json(null);
    }
};

export const getStockMovements = async (req: AuthRequest, res: Response) => {
    try {
        const { data, error } = await supabase.from('stock_movements').select('*').eq('stock_item_id', req.params.id);
        if (error && error.code !== '42P01') throw error;
        res.json(toCamelCase(data || []));
    } catch (error: unknown) {
        res.json([]);
    }
};

export const getStockAuditLogs = async (req: AuthRequest, res: Response) => {
    try {
        const { data, error } = await supabase.from('stock_audit_logs').select('*').eq('stock_item_id', req.params.id);
        if (error && error.code !== '42P01') throw error;
        res.json(toCamelCase(data || []));
    } catch (error: unknown) {
        res.json([]);
    }
};

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

export const updateStockItem = async (req: AuthRequest, res: Response) => {
    try {
        const updateData = toSnakeCase(req.body);
        const { data, error } = await supabase.from('stock_items').update(updateData).eq('id', req.params.id).select().single();
        if (error) throw error;
        res.json(toCamelCase(data));
    } catch (error: unknown) {
        res.status(500).json({ error: error instanceof Error ? error.message : 'Unknown error' });
    }
};

export const deleteStockItem = async (req: AuthRequest, res: Response) => {
    try {
        await supabase.from('stock_items').delete().eq('id', req.params.id);
        res.status(204).send();
    } catch (error: unknown) {
        res.status(204).send();
    }
};
export const adjustStock = async (req: AuthRequest, res: Response) => {
    try {
        const { id } = req.params;
        const updateData = toSnakeCase(req.body);
        const { data, error } = await supabase.from('stock_items').update(updateData).eq('id', id).select().single();
        if (error) throw error;
        res.json(toCamelCase(data));
    } catch (error: unknown) {
        res.status(500).json({ error: error instanceof Error ? error.message : 'Unknown error' });
    }
};

export const consumeStock = async (req: AuthRequest, res: Response) => {
    try {
        const { id } = req.params;
        const { quantity } = req.body;
        const { data: item, error: fetchError } = await supabase.from('stock_items').select('quantity').eq('id', id).single();
        if (fetchError) throw fetchError;
        
        const newQuantity = (item.quantity || 0) - (quantity || 0);
        const { data, error } = await supabase.from('stock_items').update({ quantity: newQuantity }).eq('id', id).select().single();
        if (error) throw error;
        
        res.json(toCamelCase(data));
    } catch (error: unknown) {
        res.status(500).json({ error: error instanceof Error ? error.message : 'Unknown error' });
    }
};

export const updateStockMovement = async (req: AuthRequest, res: Response) => {
    try {
        const { id } = req.params;
        const { data, error } = await supabase.from('stock_movements').update(req.body).eq('id', id).select().single();
        if (error) throw error;
        res.json(toCamelCase(data));
    } catch (error: unknown) {
        res.status(500).json({ error: error instanceof Error ? error.message : 'Unknown error' });
    }
};

export const deleteStockMovement = async (req: AuthRequest, res: Response) => {
    try {
        const { id } = req.params;
        await supabase.from('stock_movements').delete().eq('id', id);
        res.status(204).send();
    } catch (error: unknown) {
        res.status(500).json({ error: error instanceof Error ? error.message : 'Unknown error' });
    }
};
