import { Request, Response } from 'express';
import Instrument from '../models/Instrument.js';
import { IAppUser } from '../middleware/authMiddleware.js';

interface AuthRequest extends Request {
    appUser?: IAppUser;
}

export const createInstrument = async (req: AuthRequest, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const { name, type, manufacturer, modelName, serialNumber, calibrationDate, calibrationExpirationDate, certificateUrl, notes } = req.body;

        const existing = await Instrument.findOne({ organizationId, serialNumber });
        if (existing) {
            return res.status(400).json({ error: 'Já existe um instrumento com este número de série.' });
        }

        // Determinar status inicial baseado na validade
        let status = 'active';
        if (calibrationExpirationDate && new Date(calibrationExpirationDate) < new Date()) {
            status = 'expired';
        }

        const instrument = await Instrument.create({
            organizationId,
            name,
            type,
            manufacturer,
            modelName,
            serialNumber,
            calibrationDate,
            calibrationExpirationDate,
            certificateUrl,
            status,
            notes
        });

        res.status(201).json(instrument);
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

export const getInstruments = async (req: AuthRequest, res: Response) => {
    try {
        const organizationId = req.appUser?.organizationId;
        const { status } = req.query;

        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const query: any = { organizationId };
        if (status) query.status = status;

        const instruments = await Instrument.find(query).sort({ name: 1 });
        res.json(instruments);
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

export const updateInstrument = async (req: AuthRequest, res: Response) => {
    try {
        const { id } = req.params;
        const organizationId = req.appUser?.organizationId;

        // Recalcular status se data de validade mudar
        const updates = { ...req.body };
        if (updates.calibrationExpirationDate) {
            if (new Date(updates.calibrationExpirationDate) < new Date()) {
                updates.status = 'expired';
            } else if (updates.status === 'expired') {
                // Se estava expirado e a data é futura, reativar (se o usuário não setou outro status)
                updates.status = 'active';
            }
        }

        const instrument = await Instrument.findOneAndUpdate(
            { _id: id, organizationId },
            updates,
            { new: true }
        );

        if (!instrument) return res.status(404).json({ error: 'Instrumento não encontrado.' });
        res.json(instrument);
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};

export const deleteInstrument = async (req: AuthRequest, res: Response) => {
    try {
        const { id } = req.params;
        const organizationId = req.appUser?.organizationId;

        const deleted = await Instrument.findOneAndDelete({ _id: id, organizationId });
        if (!deleted) return res.status(404).json({ error: 'Instrumento não encontrado.' });

        res.status(204).send();
    } catch (error: unknown) {
        const message = error instanceof Error ? error.message : 'Unknown error';
        res.status(500).json({ error: message });
    }
};
