import { Request, Response } from 'express';
import db from '../../database/models/index.js';
const { Opportunity, Application, User, AuditLog } = db;
import { Op } from 'sequelize';
import { AuthRequest } from '../../types/express.types.js';
import { AUDIT_ACTIONS } from '../../common/config/constants.js';

export const getOpportunities = async (req: Request, res: Response) => {
    try {
        const { status, locationId, districtId } = req.query as any;
        const where: any = {};

        if (status) where.status = status;
        const targetDistrictId = districtId || locationId;
        if (targetDistrictId) where.districtId = targetDistrictId;

        const opportunities = await Opportunity.findAll({
            where,
            include: [
                { model: Application, as: 'application', attributes: ['id', 'applicationId', 'overallStatus'] }
            ],
            order: [['createdAt', 'DESC']]
        });

        res.json({ success: true, data: opportunities });
    } catch (error) {
        console.error('Get opportunities error:', error);
        res.status(500).json({ success: false, message: 'Error fetching opportunities' });
    }
};

export const createOpportunity = async (req: AuthRequest, res: Response) => {
    try {
        const {
            leadSource, leadName, contactNumber, email,
            locationId, districtId, city,
            opportunityType, priority, capacity, notes
        } = req.body;

        const opportunity = await Opportunity.create({
            leadSource,
            leadName,
            contactNumber,
            email,
            districtId: districtId || locationId,
            city: city || 'Unknown', // Fallback
            opportunityType,
            priority,
            capacity: capacity || '1', // Fallback
            notes,
            status: 'New',
            assignedTo: req.user?.id
        });

        await AuditLog.create({
            userId: req.user?.id,
            action: AUDIT_ACTIONS.CREATED,
            entityType: 'opportunity',
            entityId: opportunity.id
        });

        res.status(201).json({ success: true, data: opportunity, message: 'Opportunity created successfully' });
    } catch (error) {
        console.error('Create opportunity error:', error);
        res.status(500).json({ success: false, message: 'Error creating opportunity' });
    }
};

export const updateOpportunity = async (req: AuthRequest, res: Response) => {
    try {
        const { id } = req.params;
        const updateData = req.body;

        const opportunity = await Opportunity.findByPk(id);
        if (!opportunity) return res.status(404).json({ success: false, message: 'Opportunity not found' });

        await opportunity.update(updateData);

        res.json({ success: true, message: 'Opportunity updated successfully' });
    } catch (error) {
        console.error('Update opportunity error:', error);
        res.status(500).json({ success: false, message: 'Error updating opportunity' });
    }
};

export const convertToApplication = async (req: AuthRequest, res: Response) => {
    try {
        const { id } = req.params; // Opportunity ID

        const opportunity = await Opportunity.findByPk(id);
        if (!opportunity) return res.status(404).json({ success: false, message: 'Opportunity not found' });

        if (opportunity.status === 'Converted') {
            return res.status(400).json({ success: false, message: 'Opportunity already converted' });
        }

        // Logic to create Application skeleton or return data for frontend to pre-fill
        // For API, we might just mark Op as converted if Application creation happens separately,
        // OR we create the Application here explicitly.
        // Let's assume this action marks it ready and maybe creates a draft Application.

        await opportunity.update({ status: 'Converted' });

        res.json({ success: true, message: 'Opportunity marked as converted' });
    } catch (error) {
        console.error('Convert opportunity error:', error);
        res.status(500).json({ success: false, message: 'Error converting opportunity' });
    }
};
