import { NextRequest, NextResponse } from "next/server";
import { Pool } from "pg";
import { requireAdmin, requireSuperAdmin } from "@/lib/auth-utils";

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
});

// GET /api/admin/roles - List all roles
export async function GET(request: NextRequest) {
  const { error } = await requireAdmin();
  if (error) return error;

  try {
    const result = await pool.query(`
      SELECT 
        r.id, r.name, r.description, r.permissions, r.is_system, r.created_at,
        COUNT(DISTINCT u.id) as user_count
      FROM "role" r
      LEFT JOIN "user" u ON u.role = r.name
      GROUP BY r.id
      ORDER BY r.is_system DESC, r.name ASC
    `);

    return NextResponse.json({ roles: result.rows });
  } catch (error) {
    console.error("Error fetching roles:", error);
    return NextResponse.json(
      { error: "Failed to fetch roles" },
      { status: 500 }
    );
  }
}

// POST /api/admin/roles - Create a new role
export async function POST(request: NextRequest) {
  const { error } = await requireSuperAdmin();
  if (error) return error;

  try {
    const body = await request.json();
    const { name, description, permissions } = body;

    if (!name) {
      return NextResponse.json(
        { error: "Role name is required" },
        { status: 400 }
      );
    }

    // Check if role already exists
    const existingRole = await pool.query(
      'SELECT id FROM "role" WHERE name = $1',
      [name]
    );

    if (existingRole.rows.length > 0) {
      return NextResponse.json(
        { error: "Role with this name already exists" },
        { status: 409 }
      );
    }

    const id = `role_${crypto.randomUUID().replace(/-/g, "").slice(0, 12)}`;
    const result = await pool.query(
      `INSERT INTO "role" (id, name, description, permissions, is_system, created_at, updated_at)
       VALUES ($1, $2, $3, $4, false, NOW(), NOW())
       RETURNING id, name, description, permissions, is_system, created_at`,
      [id, name, description || null, JSON.stringify(permissions || {})]
    );

    return NextResponse.json({ role: result.rows[0] }, { status: 201 });
  } catch (error) {
    console.error("Error creating role:", error);
    return NextResponse.json(
      { error: "Failed to create role" },
      { status: 500 }
    );
  }
}
