import { NextRequest, NextResponse } from 'next/server';
import pool from '@/lib/db';
import { verifyToken, TokenPayload } from '@/lib/auth';
import { RowDataPacket, ResultSetHeader } from 'mysql2';
// Email import removed - using dynamic import for sendMessageNotification in POST handler

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();

            // Fetch full sender details for notification
            const [senderDetails] = await pool.query<RowDataPacket[]>(
                `SELECT full_name, email, mobile, personnummer, address, zip_code, city FROM users WHERE id = ?`,
                [user.userId]
            );
            const sender = senderDetails[0];

            // Send ONE email to CONTACT_EMAIL with premium template
            const { sendMessageNotification } = await import('@/lib/email');
            const adminEmail = process.env.CONTACT_EMAIL || 'info@nordicstorium.se';

            await sendMessageNotification(
                adminEmail,
                `Nytt kundmeddelande: ${subject}`,
                sender.full_name || 'Kund',
                sender.email,
                sender.mobile,
                sender.personnummer,
                sender.address,
                sender.zip_code,
                sender.city,
                message,
                `${process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'}/admin/messages`,
                'Svara i Adminpanelen',
                true // Customer is sender
            );

            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 });
    }
}
