import { NextResponse } from 'next/server';
import { query, execute } from '@/lib/db';
import { createToken } from '@/lib/auth';
import { cookies } from 'next/headers';

export async function POST(request: Request) {
    try {
        const { email, code } = await request.json();

        console.log('[OTP Verify] Received:', { email, code });

        if (!email || !code) {
            return NextResponse.json({ error: 'Email and OTP code are required' }, { status: 400 });
        }

        // Check OTP
        console.log('[OTP Verify] Querying: admin_email =', email, 'code =', code);
        const otps: any = await query('SELECT * FROM admin_otps WHERE admin_email = ? AND code = ?', [email, code]);
        console.log('[OTP Verify] Query result:', JSON.stringify(otps));
        
        if (!otps || otps.length === 0) {
            // Debug: show all OTPs for this email
            const allOtps: any = await query('SELECT * FROM admin_otps WHERE admin_email = ?', [email]);
            console.log('[OTP Verify] All OTPs for email:', JSON.stringify(allOtps));
            return NextResponse.json({ error: 'Invalid OTP' }, { status: 401 });
        }

        const otp = otps[0];
        const now = new Date();
        console.log('[OTP Verify] Expires at:', otp.expires_at, 'Now:', now.toISOString(), 'Expired:', new Date(otp.expires_at) < now);
        if (new Date(otp.expires_at) < now) {
            return NextResponse.json({ error: 'OTP has expired' }, { status: 401 });
        }

        // Get admin details — try with is_active column, fallback if missing
        let admins: any[];
        try {
            admins = await query('SELECT id, email, role, is_active FROM admins WHERE email = ?', [email]);
        } catch (e) {
            // Old schema without is_active
            admins = await query('SELECT id, email, role FROM admins WHERE email = ?', [email]);
        }
        
        if (!admins || admins.length === 0) {
            return NextResponse.json({ error: 'Admin not found' }, { status: 404 });
        }

        const admin = admins[0];

        // Check if admin is active (default to active if column missing)
        if (admin.is_active === 0) {
            return NextResponse.json({ error: 'Access revoked. Contact Super Admin.' }, { status: 403 });
        }

        // Success - Generate session token
        const token = await createToken({
            id: admin.id,
            email: admin.email,
            role: admin.role || 'ADMIN',
            isAdmin: true
        });

        // Set secure cookie
        const cookieStore = await cookies();
        cookieStore.set('admin_session', token, {
            httpOnly: true,
            secure: process.env.NODE_ENV === 'production',
            sameSite: 'lax',
            maxAge: 60 * 60 * 2, // 2 hours
            path: '/',
        });

        // Cleanup OTP
        await execute('DELETE FROM admin_otps WHERE admin_email = ?', [email]);
        
        // Log admin login to audit table
        await execute('INSERT INTO UserAction (id, userId, actionType, entityType, metadata) VALUES (?, ?, ?, ?, ?)', [
            `log_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`,
            admin.email, // using email as userId for admins since they are distinct
            'LOGIN',
            'ADMIN_PORTAL',
            'Admin successfully verified OTP and logged in.'
        ]);

        return NextResponse.json({ success: true, message: 'Logged in successfully' });
    } catch (error) {
        console.error('OTP verification error:', error);
        return NextResponse.json({ error: 'An internal server error occurred' }, { status: 500 });
    }
}
