import { Request, Response } from 'express';
import { AuthRequest } from '../middleware/auth';
import * as fileService from '../services/fileService';

export const convertToFile = async (req: AuthRequest, res: Response) => {
    try {
        if (!req.user) {
            return res.status(401).json({ error: 'Unauthorized' });
        }

        const leadId = parseInt(req.params.leadId, 10);
        const { fileType, dsaCode } = req.body;
        const file = await fileService.convertLeadToFile(leadId, fileType, dsaCode, req.user.userId);
        res.json(file);
    } catch (error: any) {
        res.status(400).json({ error: error.message || 'Failed to convert to file' });
    }
};

export const createPayout = async (req: AuthRequest, res: Response) => {
    try {
        if (!req.user) {
            return res.status(401).json({ error: 'Unauthorized' });
        }

        const { leadId, dsaId, amount } = req.body;
        const payout = await fileService.createDSAPayout(leadId, dsaId, amount, req.user.userId);
        res.status(201).json(payout);
    } catch (error: any) {
        res.status(400).json({ error: error.message || 'Failed to create payout' });
    }
};

export const generateReport = async (req: Request, res: Response) => {
    try {
        const { reportType, startDate, endDate } = req.query;
        const report = await fileService.generateReport(reportType as string, startDate as string, endDate as string);
        res.json(report);
    } catch (error: any) {
        res.status(500).json({ error: error.message || 'Failed to generate report' });
    }
};

export const scoreLead = async (req: Request, res: Response) => {
    try {
        const leadId = parseInt(req.params.leadId, 10);
        const score = await fileService.scoreLeadAI(leadId);
        res.json(score);
    } catch (error: any) {
        res.status(500).json({ error: error.message || 'Failed to score lead' });
    }
};

export const checkEligibility = async (req: Request, res: Response) => {
    try {
        const leadId = parseInt(req.params.leadId, 10);
        const eligibility = await fileService.checkEligibility(leadId);
        res.json(eligibility);
    } catch (error: any) {
        res.status(500).json({ error: error.message || 'Failed to check eligibility' });
    }
};
