import { NextResponse } from "next/server"
import { sql } from "@/lib/db"

// GET - List all verification requests (admin)
export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url)
    const status = searchParams.get("status") || "pending"
    const page = Number.parseInt(searchParams.get("page") || "1")
    const limit = Number.parseInt(searchParams.get("limit") || "20")
    const offset = (page - 1) * limit

    const requests = await sql`
      SELECT 
        vr.*,
        a.name as artist_name,
        a.avatar_url as artist_avatar,
        a.total_streams,
        a.total_followers,
        a.monthly_listeners,
        u.name as reviewer_name
      FROM verification_requests vr
      JOIN artists a ON vr.artist_id = a.id
      LEFT JOIN users u ON vr.reviewed_by = u.id
      WHERE ${status === "all" ? sql`1=1` : sql`vr.status = ${status}`}
      ORDER BY vr.created_at DESC
      LIMIT ${limit} OFFSET ${offset}
    `

    const countResult = await sql`
      SELECT COUNT(*) as total FROM verification_requests vr
      WHERE ${status === "all" ? sql`1=1` : sql`vr.status = ${status}`}
    `

    const currentMonth = new Date()
    currentMonth.setDate(1)
    currentMonth.setHours(0, 0, 0, 0)

    const monthlyStats = await sql`
      SELECT 
        status,
        COUNT(*) as count
      FROM verification_requests
      WHERE reviewed_at >= ${currentMonth.toISOString()}
        AND status IN ('approved', 'rejected')
      GROUP BY status
    `

    const approvedThisMonth = monthlyStats.find((s) => s.status === "approved")?.count || 0
    const rejectedThisMonth = monthlyStats.find((s) => s.status === "rejected")?.count || 0

    return NextResponse.json({
      requests,
      total: Number.parseInt(countResult[0].total),
      page,
      limit,
      stats: {
        approvedThisMonth: Number.parseInt(approvedThisMonth.toString()),
        rejectedThisMonth: Number.parseInt(rejectedThisMonth.toString()),
      },
    })
  } catch (error) {
    console.error("Error fetching verification requests:", error)
    return NextResponse.json({ error: "Failed to fetch requests" }, { status: 500 })
  }
}

// PATCH - Approve or reject a verification request (admin)
export async function PATCH(request: Request) {
  try {
    const body = await request.json()
    const { request_id, action, rejection_reason, admin_id } = body

    if (!request_id || !action || !admin_id) {
      return NextResponse.json({ error: "Missing required fields" }, { status: 400 })
    }

    if (!["approve", "reject"].includes(action)) {
      return NextResponse.json({ error: "Invalid action" }, { status: 400 })
    }

    // Get the verification request
    const verificationRequest = await sql`
      SELECT * FROM verification_requests WHERE id = ${request_id}
    `

    if (!verificationRequest[0]) {
      return NextResponse.json({ error: "Request not found" }, { status: 404 })
    }

    const artistId = verificationRequest[0].artist_id
    const newStatus = action === "approve" ? "approved" : "rejected"

    // Update the verification request
    await sql`
      UPDATE verification_requests 
      SET 
        status = ${newStatus},
        rejection_reason = ${action === "reject" ? rejection_reason : null},
        reviewed_by = ${admin_id},
        reviewed_at = NOW(),
        updated_at = NOW()
      WHERE id = ${request_id}
    `

    // If approved, update the artist's verification status
    if (action === "approve") {
      await sql`
        UPDATE artists SET is_verified = true, updated_at = NOW()
        WHERE id = ${artistId}
      `
    }

    // Create a notification for the artist
    const artistUser = await sql`
      SELECT user_id FROM artists WHERE id = ${artistId}
    `

    if (artistUser[0]?.user_id) {
      await sql`
        INSERT INTO notifications (user_id, title, message, type, action_url)
        VALUES (
          ${artistUser[0].user_id},
          ${action === "approve" ? "Verification approuvee!" : "Demande de verification refusee"},
          ${
            action === "approve"
              ? "Felicitations! Votre profil artiste est maintenant verifie. Vous avez obtenu le badge officiel."
              : `Votre demande de verification a ete refusee. ${rejection_reason || "Veuillez reessayer plus tard."}`
          },
          ${action === "approve" ? "success" : "info"},
          '/artist/settings'
        )
      `
    }

    return NextResponse.json({
      success: true,
      message: action === "approve" ? "Artist verified successfully" : "Request rejected",
    })
  } catch (error) {
    console.error("Error processing verification request:", error)
    return NextResponse.json({ error: "Failed to process request" }, { status: 500 })
  }
}
