// src/routes/api/login.ts
import type { APIContext } from "astro";
import { hashPassword, newUser, updateUser } from "@utils/auths";

export async function POST({ request, cookies, locals }: APIContext) {
  const formData = await request.formData();
  // @ts-ignore
  const user = locals.user;

  const email = formData.get("email");
  const firstName = formData.get("first_name");
  const lastName = formData.get("last_name");
  const username = formData.get("username");
  const phone = formData.get("phone");
  const address = formData.get("address");
  const id = Number(formData.get("id"));

  if (
    typeof email !== "string" ||
    typeof address !== "string" ||
    typeof phone !== "string" ||
    typeof username !== "string" ||
    typeof lastName !== "string" ||
    typeof firstName !== "string"
  ) {
    return new Response(
      JSON.stringify({
        message: "Text Inputs Only",
      }),
      {
        status: 400,
      }
    );
  }
  if (Number(user.id) !== id || !user.isAdmin) {
    return new Response(
      JSON.stringify({
        message: "Unauthorised user",
      }),
      {
        status: 403,
      }
    );
  }
  try {
    await updateUser(
      {
        email,
        firstName,
        lastName,
        username,
        phone,
        address,
      },
      id
    );

    // return a successful response
    return new Response(
      JSON.stringify({
        message: "Account Created!",
      }),
      {
        status: 201,
      }
    );
  } catch (error) {
    return new Response(
      JSON.stringify({
        message: error?.message,
      }),
      {
        status: 500,
      }
    );
  }
}
