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

interface AuthRequest extends Request {
    appUser?: IAppUser;
}

export const createPart = async (req: AuthRequest, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const payload = toSnakeCase({ ...req.body, organizationId });
        const part = await partService.createPart(payload);
        res.status(201).json(toCamelCase(part));
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

export const getPartsByProject = async (req: AuthRequest, res: Response) => {
    try {
        const { projectId } = req.params;
        const organizationId = req.appUser?.organizationId;
        const isGlobalAdmin = req.appUser?.email === 'admtracksteel@gmail.com';
        const parts = await partService.getPartsByProject(projectId as string, organizationId, isGlobalAdmin);
        res.json(toCamelCase(parts || []));
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

export const updatePart = async (req: AuthRequest, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const isGlobalAdmin = req.appUser?.email === 'admtracksteel@gmail.com';
        const part = await partService.updatePart(req.params.id as string, toSnakeCase(req.body), organizationId, isGlobalAdmin);
        res.json(toCamelCase(part));
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

export const deletePart = async (req: AuthRequest, res: Response) => {
    try {
        await partService.deletePart(req.params.id as string);
        res.status(204).send();
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

export const getAllParts = async (req: AuthRequest, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        if (!organizationId) return res.json([]);
        const parts = await partService.getPartsByOrganization(organizationId);
        res.json(toCamelCase(parts || []));
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};
