const OnboardingService = require('../services/onboarding.service');
const { asyncHandler } = require('../middleware/errorHandler');
const { sendOnboardingConfirmationEmail } = require('../services/email.service');

class OnboardingController {
    static getAllProtocols = asyncHandler(async (req, res) => {
        const protocols = OnboardingService.getAllProtocols();
        res.json({ status: 'success', data: protocols });
    });

    static getProtocolById = asyncHandler(async (req, res) => {
        const protocol = OnboardingService.getProtocolById(parseInt(req.params.id));
        res.json({ status: 'success', data: protocol });
    });

    static createProtocol = asyncHandler(async (req, res) => {
        const protocol = await OnboardingService.createProtocol(req.body, req.user.id, req.ip);
        res.status(201).json({ status: 'success', data: protocol });
    });

    static updateProtocol = asyncHandler(async (req, res) => {
        const protocol = await OnboardingService.updateProtocol(
            parseInt(req.params.id),
            req.body,
            req.user.id,
            req.ip
        );
        res.json({ status: 'success', data: protocol });
    });

    static regeneratePdf = asyncHandler(async (req, res) => {
        const protocol = await OnboardingService.regeneratePdf(
            parseInt(req.params.id),
            req.user.id,
            req.ip
        );
        res.json({ status: 'success', data: protocol });
    });

    static deleteProtocol = asyncHandler(async (req, res) => {
        const deleted = OnboardingService.deleteProtocol(
            parseInt(req.params.id),
            req.user.id,
            req.ip
        );

        if (!deleted) {
            return res.status(404).json({ status: 'error', message: 'Protokoll nicht gefunden' });
        }

        res.json({ status: 'success', message: 'Protokoll erfolgreich gelöscht' });
    });

    static sendConfirmationEmail = asyncHandler(async (req, res) => {
        const crypto = require('crypto');
        const OnboardingProtocol = require('../models/OnboardingProtocol');
        const protocol = await OnboardingService.getProtocolById(parseInt(req.params.id));
        if (!protocol.emp_private_email) {
            return res.status(400).json({ status: 'error', message: 'Keine private E-Mail-Adresse beim Mitarbeiter hinterlegt' });
        }
        const token = crypto.randomBytes(32).toString('hex');
        OnboardingProtocol.setConfirmToken(protocol.id, token);
        await sendOnboardingConfirmationEmail(protocol, token);
        res.json({ status: 'success', message: `Bestätigungsmail an ${protocol.emp_private_email} gesendet` });
    });

    static confirmByToken = asyncHandler(async (req, res) => {
        const OnboardingProtocol = require('../models/OnboardingProtocol');
        const { token } = req.params;
        const protocol = OnboardingProtocol.getByConfirmToken(token);
        if (!protocol) {
            return res.status(404).json({ status: 'error', message: 'Ungültiger oder bereits verwendeter Bestätigungslink' });
        }
        OnboardingProtocol.confirmByToken(token);
        const name = `${protocol.emp_first_name || ''} ${protocol.emp_last_name || ''}`.trim();
        res.json({ status: 'success', message: 'Übergabe erfolgreich bestätigt', data: { name, department: protocol.department } });
    });

    static getStatistics = asyncHandler(async (req, res) => {
        const stats = OnboardingService.getStatistics();
        res.json({ status: 'success', data: stats });
    });
}

module.exports = OnboardingController;
