import { NextRequest, NextResponse } from "next/server";

import {
  getHermesUrl,
  readJson,
  setAuthCookie,
  upstreamConfigurationErrorResponse,
  upstreamUnavailableResponse,
} from "@/lib/server/hermes";
import { assertSameOrigin } from "@/lib/server/request-guards";

type HermesLoginResponse = {
  access_token: string;
  expires_in: number;
  user: {
    id: number;
    username: string;
    email: string;
  };
};

export async function POST(request: NextRequest) {
  const originError = assertSameOrigin(request);

  if (originError) {
    return originError;
  }

  const credentials = await request.json();
  const hermesUrl = getHermesUrl();

  if (!hermesUrl) {
    return upstreamConfigurationErrorResponse();
  }

  let hermesResponse: Response;

  try {
    hermesResponse = await fetch(`${hermesUrl}/auth/login`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify(credentials),
      cache: "no-store",
    });
  } catch {
    return upstreamUnavailableResponse();
  }

  const data = await readJson(hermesResponse);

  if (!hermesResponse.ok) {
    return NextResponse.json(data, {
      status: hermesResponse.status,
    });
  }

  const loginData = data as HermesLoginResponse;
  const response = NextResponse.json({
    user: loginData.user,
  });

  setAuthCookie(response, loginData.access_token, loginData.expires_in);

  return response;
}
