import { NextRequest, NextResponse } from 'next/server';
import pool from '@/lib/db';
import { verifyToken, TokenPayload } from '@/lib/auth';
import { RowDataPacket, ResultSetHeader } from 'mysql2';
import { sendEmail } from '@/lib/email';

function getUserFromRequest(request: NextRequest): TokenPayload | null {
    const authHeader = request.headers.get('authorization');
    if (!authHeader?.startsWith('Bearer ')) return null;
    const token = authHeader.substring(7);
    try {
        return verifyToken(token);
    } catch {
        return null;
    }
}

// GET /api/conversations - List user's conversations
export async function GET(request: NextRequest) {
    try {
        const user = getUserFromRequest(request);
        if (!user) {
            return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
        }

        let sql: string;
        let params: (string | number)[] = [];

        if (user.role === 'admin') {
            sql = `
                SELECT 
                    c.id, c.subject, c.status, c.created_at, c.updated_at,
                    u.id as user_id, u.full_name as user_name, u.email as user_email,
                    p.id as product_id, p.name as product_name,
                    (SELECT COUNT(*) FROM messages m WHERE m.conversation_id = c.id AND m.is_read = FALSE AND m.sender_role = 'customer') as unread_count,
                    (SELECT content FROM messages m WHERE m.conversation_id = c.id ORDER BY m.created_at DESC LIMIT 1) as last_message
                FROM conversations c
                JOIN users u ON c.user_id = u.id
                LEFT JOIN products p ON c.product_id = p.id
                ORDER BY c.updated_at DESC
            `;
        } else {
            sql = `
                SELECT 
                    c.id, c.subject, c.status, c.created_at, c.updated_at,
                    p.id as product_id, p.name as product_name,
                    (SELECT COUNT(*) FROM messages m WHERE m.conversation_id = c.id AND m.is_read = FALSE AND m.sender_role = 'admin') as unread_count,
                    (SELECT content FROM messages m WHERE m.conversation_id = c.id ORDER BY m.created_at DESC LIMIT 1) as last_message
                FROM conversations c
                LEFT JOIN products p ON c.product_id = p.id
                WHERE c.user_id = ?
                ORDER BY c.updated_at DESC
            `;
            params = [user.userId];
        }

        const [rows] = await pool.query<RowDataPacket[]>(sql, params);
        return NextResponse.json(rows);
    } catch (error) {
        console.error('Error fetching conversations:', error);
        return NextResponse.json({ error: 'Server error' }, { status: 500 });
    }
}

// POST /api/conversations - Create new conversation
export async function POST(request: NextRequest) {
    try {
        const user = getUserFromRequest(request);
        if (!user) {
            return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
        }

        const body = await request.json();
        const { product_id, subject, message } = body;

        if (!subject || !message) {
            return NextResponse.json({ error: 'Subject and message are required' }, { status: 400 });
        }

        const connection = await pool.getConnection();
        try {
            await connection.beginTransaction();

            const [convResult] = await connection.query<ResultSetHeader>(
                `INSERT INTO conversations (user_id, product_id, subject) VALUES (?, ?, ?)`,
                [user.userId, product_id || null, subject]
            );
            const conversationId = convResult.insertId;

            await connection.query<ResultSetHeader>(
                `INSERT INTO messages (conversation_id, sender_id, sender_role, content) VALUES (?, ?, 'customer', ?)`,
                [conversationId, user.userId, message]
            );

            await connection.commit();

            // Notify admins via email if they are offline
            const [admins] = await pool.query<RowDataPacket[]>(
                `SELECT id, email FROM users WHERE role = 'admin'`
            );

            for (const admin of admins) {
                // Check if admin is online (has active session)
                const [sessions] = await pool.query<RowDataPacket[]>(
                    `SELECT COUNT(*) as count FROM user_sessions 
                     WHERE user_id = ? AND expires_at > NOW()`,
                    [admin.id]
                );

                const isOnline = sessions[0].count > 0;

                if (!isOnline) {
                    await sendEmail(
                        admin.email,
                        `Nytt meddelande: ${subject}`,
                        `
                            <h2>Nytt kundmeddelande</h2>
                            <p><strong>Från:</strong> ${user.email}</p>
                            <p><strong>Ämne:</strong> ${subject}</p>
                            <p><strong>Meddelande:</strong></p>
                            <blockquote style="border-left: 3px solid #ccc; padding-left: 10px; margin: 10px 0;">${message}</blockquote>
                            <p><a href="${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/admin/messages/${conversationId}">Svara här</a></p>
                        `
                    );
                }
            }

            return NextResponse.json({
                success: true,
                conversationId,
                message: 'Meddelande skickat!'
            }, { status: 201 });
        } catch (error) {
            await connection.rollback();
            throw error;
        } finally {
            connection.release();
        }
    } catch (error) {
        console.error('Error creating conversation:', error);
        return NextResponse.json({ error: 'Server error' }, { status: 500 });
    }
}
