import { sql } from "@/lib/db"
import { type NextRequest, NextResponse } from "next/server"
import { v4 as uuidv4 } from "uuid"
import { authRateLimit } from "@/lib/rate-limit"

export async function POST(request: NextRequest) {
  try {
    const { email, password } = await request.json()

    if (!email || !password) {
      return NextResponse.json({ error: "Email et mot de passe requis" }, { status: 400 })
    }

    const clientIp = request.headers.get("x-forwarded-for") || request.headers.get("x-real-ip") || "anonymous"
    const rateLimitResult = await authRateLimit(`${clientIp}:${email.toLowerCase()}`)

    if (!rateLimitResult.allowed) {
      console.log(`[v0] [Auth] Rate limit exceeded for ${email} from IP: ${clientIp}`)
      return NextResponse.json(
        { error: "Trop de tentatives de connexion. Veuillez réessayer plus tard." },
        { status: 429 },
      )
    }

    console.log(`[v0] [Auth] Login attempt for ${email}`)

    // Find user by email
    const users = await sql`
      SELECT id, email, password_hash, name, avatar_url, role, subscription_type, is_active
      FROM users
      WHERE email = ${email.toLowerCase()}
    `

    if (users.length === 0) {
      return NextResponse.json({ error: "Email ou mot de passe incorrect" }, { status: 401 })
    }

    const user = users[0]

    if (!user.is_active) {
      return NextResponse.json({ error: "Compte désactivé" }, { status: 403 })
    }

    let isValidPassword = false

    // Check if this is a demo account with known password
    const demoAccounts = ["admin@musicapp.com", "artist@musicapp.com", "user@musicapp.com"]
    if (demoAccounts.includes(email.toLowerCase()) && password === "admin123") {
      isValidPassword = true
    } else {
      // For real accounts, try bcrypt comparison
      try {
        const bcrypt = await import("bcryptjs")
        isValidPassword = await bcrypt.compare(password, user.password_hash)
      } catch (e) {
        // If bcrypt fails, try direct comparison (for migration period)
        isValidPassword = user.password_hash === password
      }
    }

    if (!isValidPassword) {
      return NextResponse.json({ error: "Email ou mot de passe incorrect" }, { status: 401 })
    }

    // Create session token
    const token = uuidv4()
    const expiresAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) // 30 days

    await sql`
      INSERT INTO user_sessions (user_id, token, expires_at)
      VALUES (${user.id}, ${token}, ${expiresAt})
    `

    // Update last login
    await sql`
      UPDATE users SET last_login_at = CURRENT_TIMESTAMP WHERE id = ${user.id}
    `

    // Get artist profile if user is an artist
    let artistProfile = null
    if (user.role === "artist") {
      const artists = await sql`
        SELECT id, name, avatar_url, is_verified
        FROM artists
        WHERE user_id = ${user.id}
      `
      if (artists.length > 0) {
        artistProfile = artists[0]
      }
    }

    return NextResponse.json({
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
        avatar_url: user.avatar_url,
        role: user.role,
        subscription_type: user.subscription_type,
        artist: artistProfile,
      },
      token,
      expires_at: expiresAt,
    })
  } catch (error) {
    console.error("[v0] [Auth] Login error:", error)
    return NextResponse.json({ error: "Erreur de connexion" }, { status: 500 })
  }
}
