"use server";

import { SignupFormSchema, FormState } from "../../lib/definitions";
import { login } from "@/lib/session";

const apiUrl = process.env.NEXT_SERVER_API_URL;

export async function signup(state: FormState, formData: FormData) {
  // Validate form fields
  const validatedFields = SignupFormSchema.safeParse({
    name: formData.get("name"),
    password: formData.get("password"),
  });

  // If any form fields are invalid, return early
  if (!validatedFields.success) {
    return {
      errors: validatedFields.error.flatten().fieldErrors,
    };
  }

  // Call the provider or db to create a user...
  const name = formData.get("name") as string;
  const password = formData.get("password") as string;

  const payload = {
    name,
    password,
  };

  try {
    const response = await fetch(`${apiUrl}/auth/signup`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(payload),
      cache: "no-store",
    });

    if (!response.ok) {
      console.error("Response status:", response.status);
      throw new Error("Failed to submit form");
    } else {
    }
  } catch (error) {
    console.error("Error submitting form:", error);
    throw new Error("An error occurred while submitting the form.");
  }
}

export async function signin(name: string, password: string) {
  const payload = {
    name,
    password,
  };

  try {
    const response = await fetch(`${apiUrl}/auth/signin`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(payload),
      cache: "no-store",
    });

    if (!response.ok) {
      return false;
    }

    await login(name);
    return true;
  } catch (error) {
    console.error("Error submitting form:", error);
    throw new Error("An error occurred while submitting the form.");
  }
}
