import { Request, Response } from 'express';
import { WorkflowTemplate } from '../models';
import logger from '../utils/logger';

export const createTemplate = async (req: Request, res: Response) => {
    try {
        const { name, description, category, priority, estimatedTime, approvers, suggestedSLA } = req.body;
        const userId = (req as any).user?.userId;

        const template = await WorkflowTemplate.create({
            templateName: name,
            templateDescription: description,
            templateCategory: category,
            approvalLevelsConfig: approvers,
            defaultTatHours: suggestedSLA,
            createdBy: userId,
            isActive: true,
            isSystemTemplate: false,
            usageCount: 0
        });

        res.status(201).json({
            success: true,
            message: 'Workflow template created successfully',
            data: template
        });
    } catch (error) {
        logger.error('Error creating workflow template:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to create workflow template',
            error: error instanceof Error ? error.message : 'Unknown error'
        });
    }
};

export const getTemplates = async (req: Request, res: Response) => {
    try {
        const templates = await WorkflowTemplate.findAll({
            where: { isActive: true },
            order: [['createdAt', 'DESC']]
        });

        res.status(200).json({
            success: true,
            data: templates
        });
    } catch (error) {
        logger.error('Error fetching workflow templates:', error);
        res.status(500).json({
            success: false,
            message: 'Failed to fetch workflow templates',
            error: error instanceof Error ? error.message : 'Unknown error'
        });
    }
}


export const updateTemplate = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const { name, description, category, approvers, suggestedSLA, isActive } = req.body;

        const updates: any = {};
        if (name) updates.templateName = name;
        if (description) updates.templateDescription = description;
        if (category) updates.templateCategory = category;
        if (approvers) updates.approvalLevelsConfig = approvers;
        if (suggestedSLA) updates.defaultTatHours = suggestedSLA;
        if (isActive !== undefined) updates.isActive = isActive;

        const template = await WorkflowTemplate.findByPk(id);

        if (!template) {
            return res.status(404).json({
                success: false,
                message: 'Workflow template not found'
            });
        }

        await template.update(updates);

        return res.status(200).json({
            success: true,
            message: 'Workflow template updated successfully',
            data: template
        });
    } catch (error) {
        logger.error('Error updating workflow template:', error);
        return res.status(500).json({
            success: false,
            message: 'Failed to update workflow template',
            error: error instanceof Error ? error.message : 'Unknown error'
        });
    }
};

export const deleteTemplate = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const template = await WorkflowTemplate.findByPk(id);

        if (!template) {
            return res.status(404).json({
                success: false,
                message: 'Workflow template not found'
            });
        }

        // Hard delete or Soft delete based on preference. 
        // Since we have isActive flag, let's use that (Soft Delete) or just destroy if it's unused.
        // For now, let's do a hard delete to match the expectation of "Delete" in the UI 
        // unless there are FK constraints (which sequelize handles). 
        // Actually, safer to Soft Delete by setting isActive = false if we want history, 
        // but user asked for Delete. Let's do destroy.
        await template.destroy();

        return res.status(200).json({
            success: true,
            message: 'Workflow template deleted successfully'
        });
    } catch (error) {
        logger.error('Error deleting workflow template:', error);
        return res.status(500).json({
            success: false,
            message: 'Failed to delete workflow template',
            error: error instanceof Error ? error.message : 'Unknown error'
        });
    }
};
