"use server"

import { editProfileSchema } from "@/components/MyProfile/Profile/Edit/Form/schema"
import { ZodError } from "zod"

import { type State, Status } from "@/types/components/myPages/myProfile/edit"

export async function editProfile(_prevState: State, values: FormData) {
  try {
    const data = editProfileSchema.parse(Object.fromEntries(values.entries()))

    /**
     * TODO: Update profile data when endpoint from
     * API team is ready
     */

    console.info(`EditProfileSchema.Parse Data`)
    console.log(data)

    return {
      message: "All good!",
      status: Status.success,
    }
  } catch (error) {
    if (error instanceof ZodError) {
      return {
        errors: error.issues.map((issue) => ({
          message: `Server validation: ${issue.message}`,
          path: issue.path.join("."),
        })),
        message: "Invalid form data",
        status: Status.error,
      }
    }

    console.info(`EditProfile Server Action Error`)
    console.error(error)

    return {
      message: "Something went wrong. Please try again.",
      status: Status.error,
    }
  }
}
