import { sql } from "@/lib/db"
import { type NextRequest, NextResponse } from "next/server"
import bcrypt from "bcryptjs"
import { v4 as uuidv4 } from "uuid"

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

    if (!email || !password || !name) {
      return NextResponse.json({ error: "Tous les champs sont requis" }, { status: 400 })
    }

    // Check if email already exists
    const existingUsers = await sql`
      SELECT id FROM users WHERE email = ${email.toLowerCase()}
    `

    if (existingUsers.length > 0) {
      return NextResponse.json({ error: "Cet email est déjà utilisé" }, { status: 409 })
    }

    // Hash password
    const passwordHash = await bcrypt.hash(password, 10)

    // Create user
    const newUsers = await sql`
      INSERT INTO users (email, password_hash, name, role)
      VALUES (${email.toLowerCase()}, ${passwordHash}, ${name}, ${role})
      RETURNING id, email, name, avatar_url, role, subscription_type
    `

    const user = newUsers[0]

    // Create default user settings
    await sql`
      INSERT INTO user_settings (user_id)
      VALUES (${user.id})
    `

    // If artist, create artist profile
    let artistProfile = null
    if (role === "artist") {
      const artists = await sql`
        INSERT INTO artists (user_id, name)
        VALUES (${user.id}, ${name})
        RETURNING id, name, avatar_url, is_verified
      `
      artistProfile = artists[0]
    }

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

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

    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("Signup error:", error)
    return NextResponse.json({ error: "Erreur lors de l'inscription" }, { status: 500 })
  }
}
