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

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/unread - Get unread message count
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 COUNT(*) as count 
                FROM messages m
                JOIN conversations c ON m.conversation_id = c.id
                WHERE m.is_read = FALSE AND m.sender_role = 'customer'
            `;
        } else {
            sql = `
                SELECT COUNT(*) as count 
                FROM messages m
                JOIN conversations c ON m.conversation_id = c.id
                WHERE c.user_id = ? AND m.is_read = FALSE AND m.sender_role = 'admin'
            `;
            params = [user.userId];
        }

        const [rows] = await pool.query<RowDataPacket[]>(sql, params);

        return NextResponse.json({ count: rows[0].count });
    } catch (error) {
        console.error('Error fetching unread count:', error);
        return NextResponse.json({ error: 'Server error' }, { status: 500 });
    }
}
