import { Request, Response } from 'express';
import * as dataSheetService from '../services/dataSheetService.js';
import { toCamelCase, toSnakeCase } from '../utils/caseMapper.js';
import { IAppUser } from '../middleware/authMiddleware.js';

interface AuthRequest extends Request {
    appUser?: IAppUser;
}

export const getAllDataSheets = async (req: AuthRequest, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const sheets = await dataSheetService.getAllDataSheets(organizationId);
        res.json(toCamelCase(sheets));
    } catch (error: unknown) {
        res.json([]);
    }
};

export const extractData = async (req: AuthRequest, res: Response) => {
    try {
        const file = req.file;
        if (!file) {
            return res.status(400).json({ error: 'File is required' });
        }
        res.json({ extracted: true });
    } catch (error: unknown) {
        res.json({ extracted: false });
    }
};

export const createDataSheet = async (req: AuthRequest, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const payload = { ...req.body, organization_id: organizationId };
        const newSheet = await dataSheetService.createDataSheet(toSnakeCase(payload));
        res.status(201).json(toCamelCase(newSheet));
    } catch (error: unknown) {
        res.status(400).json({ error: (error as any).message });
    }
};

export const deleteDataSheet = async (req: AuthRequest, res: Response) => {
    try {
        const { id } = req.params;
        await dataSheetService.deleteDataSheet(id as string);
        res.status(204).send();
    } catch (error: unknown) {
        res.status(500).json({ error: (error as any).message });
    }
};

export const updateDataSheet = async (req: AuthRequest, res: Response) => {
    try {
        const id = req.params.id as string;
        const updatedSheet = await dataSheetService.updateDataSheet(id, toSnakeCase(req.body));
        res.json(toCamelCase(updatedSheet || req.body));
    } catch (error: unknown) {
        res.status(400).json({ error: (error as any).message });
    }
};

export const getFile = async (req: AuthRequest, res: Response) => {
    try {
        res.status(404).json({ error: 'File not found' });
    } catch (error: unknown) {
        res.status(500).json({ error: 'File not found' });
    }
};