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

// GET - Check verification status for an artist
export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url)
    const artistId = searchParams.get("artist_id")

    if (!artistId) {
      return NextResponse.json({ error: "Artist ID required" }, { status: 400 })
    }

    // Get the latest verification request for this artist
    const requests = await sql`
      SELECT 
        vr.*,
        u.name as reviewer_name
      FROM verification_requests vr
      LEFT JOIN users u ON vr.reviewed_by = u.id
      WHERE vr.artist_id = ${artistId}
      ORDER BY vr.created_at DESC
      LIMIT 1
    `

    // Also check if artist is already verified
    const artist = await sql`
      SELECT is_verified FROM artists WHERE id = ${artistId}
    `

    return NextResponse.json({
      is_verified: artist[0]?.is_verified || false,
      request: requests[0] || null,
    })
  } catch (error) {
    console.error("Error fetching verification status:", error)
    return NextResponse.json({ error: "Failed to fetch verification status" }, { status: 500 })
  }
}

// POST - Submit a new verification request
export async function POST(request: Request) {
  try {
    const body = await request.json()
    const { artist_id, reason, social_proof, documents } = body

    if (!artist_id) {
      return NextResponse.json({ error: "Artist ID required" }, { status: 400 })
    }

    // Check if artist exists and is not already verified
    const artist = await sql`
      SELECT id, is_verified, name FROM artists WHERE id = ${artist_id}
    `

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

    if (artist[0].is_verified) {
      return NextResponse.json({ error: "Artist is already verified" }, { status: 400 })
    }

    // Check for existing pending request
    const existingRequest = await sql`
      SELECT id FROM verification_requests 
      WHERE artist_id = ${artist_id} AND status = 'pending'
    `

    if (existingRequest.length > 0) {
      return NextResponse.json({ error: "A verification request is already pending" }, { status: 400 })
    }

    // Create new verification request
    const newRequest = await sql`
      INSERT INTO verification_requests (artist_id, reason, social_proof, documents)
      VALUES (
        ${artist_id}, 
        ${reason || null}, 
        ${JSON.stringify(social_proof || {})}, 
        ${JSON.stringify(documents || [])}
      )
      RETURNING *
    `

    return NextResponse.json({
      success: true,
      message: "Verification request submitted successfully",
      request: newRequest[0],
    })
  } catch (error: unknown) {
    console.error("Error submitting verification request:", error)
    // Handle unique constraint violation
    if (error instanceof Error && error.message.includes("unique")) {
      return NextResponse.json({ error: "A verification request already exists" }, { status: 400 })
    }
    return NextResponse.json({ error: "Failed to submit verification request" }, { status: 500 })
  }
}
