import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const userId = searchParams.get('userId');

    if (!userId) {
      return NextResponse.json(
        { success: false, error: 'userId query parameter is required' },
        { status: 400 }
      );
    }

    const user = await db.user.findUnique({ where: { id: userId } });
    if (!user) {
      return NextResponse.json(
        { success: false, error: 'User not found' },
        { status: 404 }
      );
    }

    const bookmarks = await db.bookmark.findMany({
      where: { userId },
      include: {
        report: {
          select: {
            id: true,
            title: true,
            scamType: true,
            status: true,
            riskLevel: true,
            riskScore: true,
            createdAt: true,
          },
        },
      },
      orderBy: { createdAt: 'desc' },
    });

    return NextResponse.json(
      { success: true, data: bookmarks },
      { status: 200 }
    );
  } catch (error) {
    console.error('List bookmarks error:', error);
    return NextResponse.json(
      { success: false, error: 'Internal server error' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { userId, reportId, entityType, entityValue, label } = body;

    if (!userId) {
      return NextResponse.json(
        { success: false, error: 'userId is required' },
        { status: 400 }
      );
    }

    const user = await db.user.findUnique({ where: { id: userId } });
    if (!user) {
      return NextResponse.json(
        { success: false, error: 'User not found' },
        { status: 404 }
      );
    }

    if (reportId) {
      const report = await db.scamReport.findUnique({ where: { id: reportId } });
      if (!report) {
        return NextResponse.json(
          { success: false, error: 'Report not found' },
          { status: 404 }
        );
      }
    }

    // Check for duplicate bookmark
    const existing = await db.bookmark.findFirst({
      where: {
        userId,
        ...(reportId ? { reportId } : {}),
        ...(entityType ? { entityType } : {}),
        ...(entityValue ? { entityValue } : {}),
      },
    });

    if (existing) {
      return NextResponse.json(
        { success: false, error: 'Bookmark already exists' },
        { status: 409 }
      );
    }

    const bookmark = await db.bookmark.create({
      data: {
        userId,
        reportId: reportId || null,
        entityType: entityType || null,
        entityValue: entityValue || null,
        label: label || null,
      },
      include: {
        report: {
          select: {
            id: true,
            title: true,
            scamType: true,
            status: true,
            riskLevel: true,
            riskScore: true,
            createdAt: true,
          },
        },
      },
    });

    return NextResponse.json(
      { success: true, data: bookmark },
      { status: 201 }
    );
  } catch (error) {
    console.error('Create bookmark error:', error);
    return NextResponse.json(
      { success: false, error: 'Internal server error' },
      { status: 500 }
    );
  }
}
