"use server";

import { CallApi } from "@/helper/api/ApiConnector";
import { cookies } from "next/headers";
import { redirect, RedirectType } from "next/navigation";

export async function LoginFormAction(formData: FormData) {
  console.log(`LoginFormAction`, formData);
  const res = await fetch(`http://localhost:8081/api/auth/signin`, {
    method: "POST",
    headers: {
      "content-type": "application/json",
    },
    body: JSON.stringify({
      email: formData.get("email") as string,
      password: formData.get("password") as string,
    }),
  }).catch((e) => console.error(e));
  // .then(async (res) => {
  const resp = await (res as Response).json();
  // console.log(resp)
  if (!resp.error) {
    const cj = await cookies();
    cj.set("ccsession", resp.result);
    redirect(`/dashboard`, RedirectType.replace);
  }
}

export async function RegisterFormAction(formData: FormData) {
  await CallApi(`/auth/signup`, "POST", {
    name: "",
    email: formData.get("email") as string,
    password: formData.get("password") as string,
  });
}
