import { requireOwner, withCors, preflight } from "@/lib/admin";
import { sql } from "@/lib/db";

type Body = {
  role?: string | null;
  email_verified?: boolean;
};

export async function OPTIONS() {
  return preflight();
}

export async function PATCH(request: Request, { id }: { id: string }) {
  const auth = await requireOwner(request);
  if ("error" in auth) return withCors(auth.error);

  try {
    const body = (await request.json()) as Body;

    if (body.role !== undefined) {
      const allowed = ["rider", "driver", "owner", null];
      if (!allowed.includes(body.role)) {
        return withCors(
          Response.json(
            { error: "Role must be rider, driver, owner or null." },
            { status: 400 },
          ),
        );
      }

      if (id === auth.userId && body.role !== "owner") {
        return withCors(
          Response.json(
            { error: "You cannot remove your own owner role." },
            { status: 400 },
          ),
        );
      }
    }

    const rows = await sql<{ id: string; role: string | null; email_verified: boolean }>`
      UPDATE users SET
        role = COALESCE(${body.role ?? null}, role),
        email_verified = COALESCE(${body.email_verified ?? null}, email_verified)
      WHERE id = ${id}
      RETURNING id, role, email_verified
    `;

    if (!rows[0]) {
      return withCors(Response.json({ error: "User not found." }, { status: 404 }));
    }

    return withCors(Response.json({ data: rows[0] }));
  } catch (error) {
    console.error("[ADMIN_USER_PATCH]: ", error);
    return withCors(
      Response.json({ error: "Internal Server Error" }, { status: 500 }),
    );
  }
}

export async function DELETE(request: Request, { id }: { id: string }) {
  const auth = await requireOwner(request);
  if ("error" in auth) return withCors(auth.error);

  if (id === auth.userId) {
    return withCors(
      Response.json(
        { error: "You cannot delete your own account." },
        { status: 400 },
      ),
    );
  }

  try {
    // rides.user_id is ON DELETE CASCADE, so a rider's rides go with them.
    const rows = await sql<{ id: string }>`
      DELETE FROM users WHERE id = ${id} RETURNING id
    `;

    if (!rows[0]) {
      return withCors(
        Response.json({ error: "User not found." }, { status: 404 }),
      );
    }

    return withCors(Response.json({ data: rows[0] }));
  } catch (error) {
    console.error("[ADMIN_USER_DELETE]: ", error);
    return withCors(
      Response.json({ error: "Internal Server Error" }, { status: 500 }),
    );
  }
}
