const express = require('express');
const router = express.Router();
const db = require('../db');
const jwt = require('jsonwebtoken');

// Mock OTP storage (In production, use Redis or a DB table with expiry)
const otpCache = new Map();

const SUPER_ADMIN_NUMBERS = ['9030295951', '7674892654'];

// Request OTP (Login or Register)
router.post('/request-otp', async (req, res) => {
    const { mobile, name, context } = req.body;
    if (!mobile) return res.status(400).json({ success: false, message: 'Mobile number required' });

    // Clean mobile number
    let cleanMobile = mobile.replace(/[^0-9]/g, '');
    if (cleanMobile.length > 10 && cleanMobile.startsWith('91')) {
        cleanMobile = cleanMobile.slice(cleanMobile.length - 10);
    } else if (cleanMobile.length === 11 && cleanMobile.startsWith('0')) {
        cleanMobile = cleanMobile.slice(1);
    }
    if (cleanMobile.length !== 10) {
        return res.status(400).json({ success: false, message: 'Invalid 10-digit mobile number' });
    }

    // Generate a 6-digit OTP
    const otp = Math.floor(100000 + Math.random() * 900000).toString();

    // Retrieve username for variables
    let username = name || 'Customer';

    // Check user existence if it's a login attempt
    if (context === 'login') {
        try {
            const userResult = await db.query('SELECT * FROM users WHERE mobile = $1', [cleanMobile]);
            if (userResult.rows.length === 0) {
                if (!SUPER_ADMIN_NUMBERS.includes(cleanMobile)) {
                    return res.status(404).json({ success: false, message: 'User not registered', code: 'needs_registration' });
                }
            }
            if (userResult.rows[0] && userResult.rows[0].name) {
                username = userResult.rows[0].name;
            } else if (SUPER_ADMIN_NUMBERS.includes(cleanMobile)) {
                username = 'Super Admin';
            }
        } catch (dbErr) {
            console.error('Database error fetching user for OTP request:', dbErr);
        }
    }

    otpCache.set(cleanMobile, otp);

    const API_KEY = process.env.FAST2SMS_KEY;
    const SENDER_ID = process.env.FAST2SMS_SENDER_ID || "SaGrup";
    const MESSAGE_ID = process.env.FAST2SMS_OTP_ID || "111904";

    // VAR 1 is: Username
    // VAR 2 is: OTP VALUE
    // VAR 3 is: Anjaneyulu Services
    // VAR 4 is: anjaneyulu.in
    // Fast2SMS DLT bulk API requires a trailing pipe symbol
    const variables_values = `${username}|${otp}|Anjaneyulu Services|anjaneyulu.in|`;

    const requestUrl = `https://www.fast2sms.com/dev/bulkV2?authorization=${encodeURIComponent(API_KEY)}&route=dlt&sender_id=${encodeURIComponent(SENDER_ID)}&message=${encodeURIComponent(MESSAGE_ID)}&variables_values=${encodeURIComponent(variables_values)}&numbers=${encodeURIComponent(cleanMobile)}&schedule_time=`;

    try {
        const response = await fetch(requestUrl, { method: 'GET' });
        const data = await response.json();

        if (data.return) {
            res.json({ success: true, message: 'OTP sent successfully', devOtp: otp }); // devOtp for testing
        } else {
            console.error('Fast2SMS send error:', data);
            res.status(500).json({ success: false, message: data.message || 'Failed to send OTP via Fast2SMS' });
        }
    } catch (err) {
        console.error(err);
        res.status(500).json({ success: false, message: 'Network error sending OTP' });
    }
});

// Resend OTP via Fast2SMS
router.post('/resend-otp', async (req, res) => {
    const { mobile } = req.body;
    if (!mobile) return res.status(400).json({ success: false, message: 'Mobile number required' });

    let cleanMobile = mobile.replace(/[^0-9]/g, '');
    if (cleanMobile.length > 10 && cleanMobile.startsWith('91')) {
        cleanMobile = cleanMobile.slice(cleanMobile.length - 10);
    } else if (cleanMobile.length === 11 && cleanMobile.startsWith('0')) {
        cleanMobile = cleanMobile.slice(1);
    }
    if (cleanMobile.length !== 10) {
        return res.status(400).json({ success: false, message: 'Invalid 10-digit mobile number' });
    }

    const API_KEY = process.env.FAST2SMS_KEY;
    const SENDER_ID = process.env.FAST2SMS_SENDER_ID || "SaGrup";
    const MESSAGE_ID = process.env.FAST2SMS_OTP_ID || "111904";

    // Retrieve existing OTP or generate a new one
    let otp = otpCache.get(cleanMobile);
    if (!otp) {
        otp = Math.floor(100000 + Math.random() * 900000).toString();
        otpCache.set(cleanMobile, otp);
    }

    // Retrieve username for variables
    let username = 'Customer';
    try {
        const userResult = await db.query('SELECT * FROM users WHERE mobile = $1', [cleanMobile]);
        if (userResult.rows[0] && userResult.rows[0].name) {
            username = userResult.rows[0].name;
        } else if (SUPER_ADMIN_NUMBERS.includes(cleanMobile)) {
            username = 'Super Admin';
        }
    } catch (dbErr) {
        console.error('Database error fetching user for OTP resend:', dbErr);
    }

    const variables_values = `${username}|${otp}|Anjaneyulu Services|anjaneyulu.in|`;
    const requestUrl = `https://www.fast2sms.com/dev/bulkV2?authorization=${encodeURIComponent(API_KEY)}&route=dlt&sender_id=${encodeURIComponent(SENDER_ID)}&message=${encodeURIComponent(MESSAGE_ID)}&variables_values=${encodeURIComponent(variables_values)}&numbers=${encodeURIComponent(cleanMobile)}&schedule_time=`;

    try {
        const response = await fetch(requestUrl, { method: 'GET' });
        const data = await response.json();

        if (data.return) {
            res.json({ success: true, message: 'OTP resent successfully' });
        } else {
            console.error('Fast2SMS resend error:', data);
            res.status(500).json({ success: false, message: data.message || 'Failed to resend OTP via Fast2SMS' });
        }
    } catch (err) {
        console.error(err);
        res.status(500).json({ success: false, message: 'Network error resending OTP' });
    }
});

// Verify & Login/Register
router.post('/verify-otp', async (req, res) => {
    const {
        mobile,
        otp,
        name,
        whatsapp_number,
        email,
        present_address,
        permanent_address,
        referred_by_name,
        referred_by_mobile,
        context
    } = req.body;

    if (!mobile) return res.status(400).json({ success: false, message: 'Mobile number required' });
    let cleanMobile = mobile.replace(/[^0-9]/g, '');
    if (cleanMobile.length > 10 && cleanMobile.startsWith('91')) {
        cleanMobile = cleanMobile.slice(cleanMobile.length - 10);
    } else if (cleanMobile.length === 11 && cleanMobile.startsWith('0')) {
        cleanMobile = cleanMobile.slice(1);
    }
    if (cleanMobile.length !== 10) {
        return res.status(400).json({ success: false, message: 'Invalid 10-digit mobile number' });
    }

    let cleanWhatsapp = whatsapp_number ? whatsapp_number.replace(/[^0-9]/g, '') : '';
    if (cleanWhatsapp.length > 10 && cleanWhatsapp.startsWith('91')) {
        cleanWhatsapp = cleanWhatsapp.slice(cleanWhatsapp.length - 10);
    } else if (cleanWhatsapp.length === 11 && cleanWhatsapp.startsWith('0')) {
        cleanWhatsapp = cleanWhatsapp.slice(1);
    }

    let cleanReferredMobile = referred_by_mobile ? referred_by_mobile.replace(/[^0-9]/g, '') : '';
    if (cleanReferredMobile.length > 10 && cleanReferredMobile.startsWith('91')) {
        cleanReferredMobile = cleanReferredMobile.slice(cleanReferredMobile.length - 10);
    } else if (cleanReferredMobile.length === 11 && cleanReferredMobile.startsWith('0')) {
        cleanReferredMobile = cleanReferredMobile.slice(1);
    }

    const storedOtp = otpCache.get(cleanMobile);
    let isVerified = false;

    // Support 123456 and 1234 as dev bypass, or verify with stored local cache
    if (otp === '123456' || otp === '1234' || otp === storedOtp) {
        isVerified = true;
    }

    if (!isVerified) {
        return res.status(401).json({ success: false, message: 'Invalid OTP' });
    }

    try {
        // Check if user exists
        let userResult = await db.query('SELECT * FROM users WHERE mobile = $1', [cleanMobile]);
        let user = userResult.rows[0];

        if (!user) {
            if (context === 'register' || SUPER_ADMIN_NUMBERS.includes(cleanMobile)) {
                const { gender, age, occupation } = req.body;

                // Validate email domain (Gmail or Yahoo only)
                if (email) {
                    const emailLower = email.toLowerCase();
                    const isGmail = emailLower.endsWith('@gmail.com');
                    const isYahoo = emailLower.endsWith('@yahoo.com') || emailLower.endsWith('@yahoo.co.in');
                    if (!isGmail && !isYahoo) {
                        return res.status(400).json({ success: false, message: 'Only Gmail and Yahoo email addresses are allowed.' });
                    }
                }

                // Determine initial role
                let role = 'customer';
                if (SUPER_ADMIN_NUMBERS.includes(cleanMobile)) {
                    role = 'super_admin';
                }

                // Create new user
                const newUser = await db.query(
                    `INSERT INTO users (
                        name, mobile, whatsapp_number, email, 
                        gender, age, occupation,
                        present_address, permanent_address, 
                        referred_by_name, referred_by_mobile, role
                    ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING *`,
                    [
                        name || 'Super Admin', cleanMobile, cleanWhatsapp || '', email || 'admin@anjaneyulu.in',
                        gender || 'Male', age || 30, occupation || 'Business',
                        present_address ? JSON.stringify(present_address) : null,
                        permanent_address ? JSON.stringify(permanent_address) : null,
                        referred_by_name || null, cleanReferredMobile || null, role
                    ]
                );
                user = newUser.rows[0];
            } else {
                return res.status(404).json({ success: false, message: 'User not registered', code: 'needs_registration' });
            }
        } else {
            // Update role if it's a Super Admin logging in for the first time (optional, safety)
            if (SUPER_ADMIN_NUMBERS.includes(cleanMobile) && user.role !== 'super_admin') {
                const updatedUser = await db.query('UPDATE users SET role = $1 WHERE id = $2 RETURNING *', ['super_admin', user.id]);
                user = updatedUser.rows[0];
            }
        }

        if (user.status === 'suspended') {
            return res.status(403).json({ success: false, message: 'Account suspended' });
        }

        // Generate JWT
        const token = jwt.sign({ id: user.id, role: user.role }, process.env.JWT_SECRET || 'anjaneyulu_secret_123');

        res.json({
            success: true,
            token,
            user: {
                id: user.id,
                unique_user_id: user.unique_user_id,
                name: user.name,
                role: user.role,
                mobile: user.mobile
            }
        });

    } catch (err) {
        console.error(err);
        res.status(500).json({ success: false, message: 'Server error during authentication' });
    }
});

module.exports = router;
