// ── Users: Collection ────────────────────────────────────────────────────────
// GET  /api/users       — List users (paginated); admin/super_admin only
// POST /api/users       — Create a new user; super_admin only
//
// Auth: GET requires admin/super_admin; POST requires super_admin

import { NextRequest, NextResponse } from "next/server"
import { query } from "@/lib/db"
import { hashPassword, getSessionUser, encryptPassword, setSessionContext } from "@/lib/auth"
import { avatarSvgUrl } from "@/lib/avatar"

// ── GET ──────────────────────────────────────────────────────────────────────

export async function GET(request: NextRequest) {
  try {
    const sessionUser = await getSessionUser()
    if (!sessionUser) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    if (sessionUser.role !== "admin" && sessionUser.role !== "super_admin") {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 })
    }

    const { searchParams } = new URL(request.url)
    const limit = parseInt(searchParams.get("limit") || "50", 10)
    const offset = parseInt(searchParams.get("offset") || "0", 10)

    // Fetch users with their role name, excluding soft-deleted records
    const result = await query(
      `SELECT u.id, u.username, u.email, u.first_name, u.last_name,
              u.is_active AS active, u.created_at, u.avatar_url,
              r.name AS role
       FROM users u
       JOIN user_roles ur ON ur.user_id = u.id
       JOIN roles r ON r.id = ur.role_id
       WHERE u.deleted_at IS NULL
       ORDER BY u.created_at DESC
       LIMIT $1 OFFSET $2`,
      [limit, offset]
    )
    const users = result.rows.map((row: any) => ({
      id: row.id,
      name: `${row.first_name} ${row.last_name}`,
      email: row.email,
      role: row.role.toLowerCase(),
      active: row.active,
      avatar: avatarSvgUrl(`${row.first_name} ${row.last_name}`),
      createdAt: row.created_at,
    }))
    return NextResponse.json({ users }, { status: 200 })
  } catch (error) {
    console.error("Error fetching users:", error)
    return NextResponse.json({ error: "Failed to fetch users" }, { status: 500 })
  }
}

// ── POST ─────────────────────────────────────────────────────────────────────

export async function POST(request: NextRequest) {
  try {
    const sessionUser = await getSessionUser()
    if (!sessionUser) {
      return NextResponse.json({ error: "Not authenticated" }, { status: 401 })
    }
    if (sessionUser.role !== "super_admin") {
      return NextResponse.json({ error: "Only super admins can create users" }, { status: 403 })
    }

    const { name, email, password, role, active } = await request.json()
    if (!name || !email || !password || !role) {
      return NextResponse.json({ error: "Name, email, password, and role are required" }, { status: 400 })
    }

    const validRoles = ["sales", "admin", "super_admin", "dev"]
    if (!validRoles.includes(role)) {
      return NextResponse.json({ error: "Invalid role" }, { status: 400 })
    }

    // Derive first/last name from full name string
    const nameParts = name.trim().split(/\s+/)
    const firstName = nameParts[0]
    const lastName = nameParts.slice(1).join(" ") || firstName
    const username = email.split("@")[0]
    const passwordHash = await hashPassword(password)
    const passwordEncrypted = await encryptPassword(password)

    await setSessionContext(sessionUser.id)

    // Insert user record with both hash (for login) and encrypted (for recovery)
    const result = await query(
      `INSERT INTO users (username, email, password_hash, password_encrypted, first_name, last_name, is_active, created_by)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
       RETURNING id`,
      [username.toLowerCase(), email.toLowerCase(), passwordHash, passwordEncrypted, firstName, lastName, active ?? true, sessionUser.id]
    )

    // Assign the requested role via the user_roles junction table
    const roleId = (
      await query(`SELECT id FROM roles WHERE LOWER(name) = LOWER($1)`, [role])
    ).rows[0]?.id

    if (roleId) {
      await query(
        `INSERT INTO user_roles (user_id, role_id, assigned_by)
         VALUES ($1, $2, $3)`,
        [result.rows[0].id, roleId, sessionUser.id]
      )
    }

    return NextResponse.json({ success: true, id: result.rows[0].id }, { status: 201 })
  } catch (error: any) {
    console.error("Error creating user:", error)
    // Handle unique constraint violations for username or email
    if (error?.constraint === "uq_users_username" || error?.constraint === "uq_users_email") {
      return NextResponse.json({ error: "A user with this email or username already exists" }, { status: 409 })
    }
    return NextResponse.json({ error: error?.message || "Failed to create user" }, { status: 500 })
  }
}
