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

export interface AuthUser {
  id: string
  email: string
  name: string
  role: string
  artistId?: string
}

export async function authenticateRequest(request: NextRequest): Promise<AuthUser | null> {
  try {
    const authHeader = request.headers.get("authorization")
    if (!authHeader) return null

    const token = authHeader.replace("Bearer ", "")
    if (!token) return null

    // Check session validity
    const sessions = await sql`
      SELECT s.*, u.id, u.email, u.name, u.role, a.id as artist_id
      FROM user_sessions s
      JOIN users u ON s.user_id = u.id
      LEFT JOIN artists a ON a.user_id = u.id
      WHERE s.token = ${token} 
        AND s.expires_at > CURRENT_TIMESTAMP
        AND u.is_active = TRUE
    `

    if (sessions.length === 0) return null

    const session = sessions[0]
    return {
      id: session.id,
      email: session.email,
      name: session.name,
      role: session.role,
      artistId: session.artist_id,
    }
  } catch (error) {
    console.error("[v0] Auth middleware error:", error)
    return null
  }
}

export function requireAuth(handler: (request: NextRequest, user: AuthUser) => Promise<NextResponse>) {
  return async (request: NextRequest) => {
    const user = await authenticateRequest(request)
    if (!user) {
      return NextResponse.json({ error: "Authentification requise" }, { status: 401 })
    }
    return handler(request, user)
  }
}

export function requireRole(roles: string[]) {
  return (handler: (request: NextRequest, user: AuthUser) => Promise<NextResponse>) => {
    return async (request: NextRequest) => {
      const user = await authenticateRequest(request)
      if (!user) {
        return NextResponse.json({ error: "Authentification requise" }, { status: 401 })
      }
      if (!roles.includes(user.role)) {
        return NextResponse.json({ error: "Accès non autorisé" }, { status: 403 })
      }
      return handler(request, user)
    }
  }
}
