import { requireAuth } from "@/lib/jwt";
import { sql } from "@/lib/db";

export async function GET(req: Request) {
  const auth = requireAuth(req);
  if ("error" in auth) return auth.error;

  try {
    const response = await sql`
      SELECT id, name, email, phone, role FROM users WHERE id = ${auth.userId}
    `;

    return Response.json({ data: response[0] ?? null });
  } catch (error) {
    console.log("[GET_USER]: ", error);

    return Response.json({ error }, { status: 500 });
  }
}

export async function PATCH(req: Request) {
  const auth = requireAuth(req);
  if ("error" in auth) return auth.error;

  const { role } = await req.json();

  if (!["rider", "driver"].includes(role)) {
    return Response.json({ error: "Invalid role." }, { status: 400 });
  }

  try {
    const response = await sql`
      UPDATE users SET role = ${role}
      WHERE id = ${auth.userId}
      RETURNING id, role
    `;

    if (response.length === 0) {
      return Response.json({ error: "User not found." }, { status: 404 });
    }

    return Response.json({ data: response[0] });
  } catch (error) {
    console.log("[PATCH_USER]: ", error);

    return Response.json({ error }, { status: 500 });
  }
}
