import { NextResponse } from "next/server";
import { db } from "../../lib/db";

export async function GET(req: Request) {
  try {
    const { searchParams } = new URL(req.url);

    const search = searchParams.get("search") || "";
    const role = searchParams.get("role") || "ALL";
    const page = Number(searchParams.get("page") || 1);
    const limit = Number(searchParams.get("limit") || 10);

    const offset = (page - 1) * limit;

    /* =====================================
    WHERE BUILDER
    ===================================== */
    let where = "WHERE 1=1";
    const params: any[] = [];

    if (search) {
      where += `
        AND (
          name LIKE ?
          OR email LIKE ?
          OR id LIKE ?
        )
      `;

      params.push(
        `%${search}%`,
        `%${search}%`,
        `%${search}%`
      );
    }

    if (role !== "ALL") {
      where += ` AND role = ? `;
      params.push(role);
    }

    /* =====================================
    TOTAL
    ===================================== */
    const [countRows]: any = await db.query(
      `
      SELECT COUNT(*) as total
      FROM users
      ${where}
      `,
      params
    );

    const total = countRows[0].total;

    /* =====================================
    DATA
    ===================================== */
    const [rows]: any = await db.query(
      `
      SELECT
        id,
        google_id,
        name,
        email,
        avatar,
        role,
        is_active,
        created_at,
        last_login_at
      FROM users
      ${where}
      ORDER BY id DESC
      LIMIT ? OFFSET ?
      `,
      [...params, limit, offset]
    );

    const users = rows.map((row: any) => ({
      id: row.id,
      google_id: row.google_id,
      name: row.name,
      email: row.email,
      avatar: row.avatar,
      role: row.role,
      is_active: Boolean(row.is_active),
      created_at: row.created_at,
      last_login_at: row.last_login_at,
    }));

    return NextResponse.json({
      users,
      total,
      page,
      limit,
    });
  } catch (error: any) {
    console.error("USERS API ERROR:", error);

    return NextResponse.json(
      {
        message: "Failed load users",
        error: error.message,
      },
      { status: 500 }
    );
  }
}