import { Request, Response } from 'express';
import db from '../../database/models/index.js';
import jwt from 'jsonwebtoken';

// Mock secret for now, should be in env
const JWT_SECRET = process.env.JWT_SECRET || 'dev-secret';

export class ProspectiveLoginController {

    static async sendOtp(req: Request, res: Response) {
        try {
            const { phone } = req.body;

            if (!phone) {
                return res.status(400).json({ message: 'Phone number is required' });
            }

            console.log(`[ProspectiveLogin] Received OTP request for phone: '${phone}'`);

            // Check if ANY application exists for this phone and prioritize shortlisted ones
            const application = await db.Application.findOne({
                where: { phone: phone },
                order: [
                    [db.sequelize.literal("CASE WHEN \"isShortlisted\" = true OR \"ddLeadShortlisted\" = true THEN 0 ELSE 1 END"), 'ASC'],
                    ['createdAt', 'DESC']
                ]
            });

            if (!application) {
                console.log(`[ProspectiveLogin] Application not found for ${phone}, returning 404`);
                return res.status(404).json({ message: 'No application found with this phone number' });
            }

            if (!application.isShortlisted && !application.ddLeadShortlisted) {
                console.log(`[ProspectiveLogin] Application found but not shortlisted`);
                return res.status(403).json({ message: 'Your application is under review. You can login only after shortlisting.' });
            }

            // Mock logic: In a real app, we would generate a random OTP and send it via SMS
            console.log(`[Mock] OTP request for ${phone}`);

            return res.status(200).json({
                message: 'OTP sent successfully',
                data: {
                    phone,
                    mockOtp: '123456'
                }
            });

        } catch (error) {
            console.error('Send OTP error:', error);
            return res.status(500).json({ message: 'Internal server error' });
        }
    }

    static async verifyOtp(req: Request, res: Response) {
        try {
            const { phone, otp } = req.body;

            if (!phone || !otp) {
                return res.status(400).json({ message: 'Phone and OTP are required' });
            }

            if (otp === '123456') {
                // Fetch the latest shortlisted application again to get details for the session
                const application = await db.Application.findOne({
                    where: { phone: phone },
                    order: [
                        [db.sequelize.literal("CASE WHEN \"isShortlisted\" = true OR \"ddLeadShortlisted\" = true THEN 0 ELSE 1 END"), 'ASC'],
                        ['createdAt', 'DESC']
                    ]
                });

                if (!application) {
                    return res.status(404).json({ message: 'Application not found' });
                }

                // Generate a real token or a mock one that Auth middleware accepts
                // Using the specific mock token format for now to bypass standard Auth middleware db check 
                // if it's strict, or we can issue a real JWT if `strategies` allow it.
                // Reverting to the mock token format we established:
                const token = 'mock-prospective-token-' + application.id;

                return res.status(200).json({
                    message: 'OTP verified successfully',
                    data: {
                        token: token,
                        user: {
                            id: application.id, // Use application ID as user ID for prospective
                            name: application.applicantName,
                            email: application.email,
                            phone: application.phone,
                            role: 'Prospective Dealer',
                            applicationId: application.applicationId
                        }
                    }
                });
            } else {
                return res.status(400).json({ message: 'Invalid OTP' });
            }

        } catch (error) {
            console.error('Verify OTP error:', error);
            return res.status(500).json({ message: 'Internal server error' });
        }
    }
}
