"use server";

import * as yup from "yup";
import { companySchema } from "@/lib/validations/companySchema";

export async function submitCompanyRegistration(formData: FormData) {
  const data = {
    companyName: formData.get("companyName")?.toString() || "",
    contactPerson: formData.get("contactPerson")?.toString() || "",
    email: formData.get("email")?.toString() || "",
    phone: formData.get("phone")?.toString() || "",
  };

  try {
    await companySchema.validate(data, { abortEarly: false });

    console.log("Valid data:", data);
  } catch (validationError) {
    if (validationError instanceof yup.ValidationError) {
      const errors = validationError.inner.map((err) => ({
        path: err.path,
        message: err.message,
      }));
      throw new Error(
        "Validation failed: " +
          errors.map((e) => `${e.path}: ${e.message}`).join(", ")
      );
    }
    throw validationError;
  }
}
