// src/routes/api/login.ts
import type { APIContext } from "astro";
import { nanoid } from "nanoid";
import { SignJWT } from "jose";
import { validateCredentials } from "@utils/auths";
import { TOKEN } from "@middleware";

// The JWT secret
const secret = new TextEncoder().encode(import.meta.env.SESSION_SECRET);

export async function POST({ request, cookies }: APIContext) {
  const formData = await request.formData();

  const email = formData.get("email");
  const password = formData.get("password");
  if (typeof email !== "string" || typeof password !== "string") {
    return new Response(
      JSON.stringify({
        message: "Text Inputs Only",
      }),
      {
        status: 400,
      }
    );
  }
  try {
    // checks for email + password combinaison
    const user = await validateCredentials({ email, password });

    if (!user) {
      // if email or password incorrect, flash a message to show the user what is the error

      return new Response(
        JSON.stringify({
          message: "Invalid email/password",
        }),
        {
          status: 403,
        }
      );
    }

    // if the credentials are valid, save the user in session
    const token = await new SignJWT({ user: { ...user, password: undefined } })
      .setProtectedHeader({ alg: "HS256" })
      .setJti(nanoid())
      .setIssuedAt()
      .setExpirationTime("2h")
      .sign(secret);

    // set JWT as a cookie
    cookies.set(TOKEN, token, {
      httpOnly: true,
      path: "/",
      maxAge: 60 * 60 * 2, // 2 hours in seconds
    });

    // return a successful response
    return new Response(
      JSON.stringify({
        message: "You're logged in!",
      }),
      {
        status: 200,
      }
    );
  } catch (error) {
    return new Response(
      JSON.stringify({
        message: error?.message,
      }),
      {
        status: 500,
      }
    );
  }
}
