"use server";

import { cookies } from "next/headers";

export const login = async (username: string, password: string): Promise<{ success: boolean, message: string, token?: string }> => {
  if (!process.env.SECNEX_AUTH_API_HOST || !process.env.SECNEX_AUTH_API_KEY) {
    return { success: false, message: "SecNex API host or key is not set" };
  }

  const cookieStore = await cookies();
  try {
    const response = await fetch(`${process.env.SECNEX_AUTH_API_HOST}/login`, {
      method: "POST",
      body: JSON.stringify({ username, password }),
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${process.env.SECNEX_AUTH_API_KEY}`,
      },
    });
    const dataResponse = await response.json();
    const body = dataResponse.body;
    cookieStore.set("token", body.token);
    if (!response.ok) {
      return { success: false, message: "Invalid username or password" };
    }
    return { success: true, message: body.message, token: body.token };
  } catch (error) {
    console.error(error);
    return { success: false, message: "Failed to login" };
  }
};