"use server"

import { parsePhoneNumber } from "libphonenumber-js"
import { redirect } from "next/navigation"
import { z } from "zod"

import { signupVerify } from "@/constants/routes/signup"
import * as api from "@/lib/api"
import { serviceServerActionProcedure } from "@/server/trpc"

import { signUpSchema } from "@/components/Forms/Signup/schema"
import { passwordValidator } from "@/utils/passwordValidator"
import { phoneValidator } from "@/utils/phoneValidator"

const registerUserPayload = z.object({
  language: z.string(),
  firstName: z.string(),
  lastName: z.string(),
  email: z.string(),
  phoneNumber: phoneValidator("Phone is required"),
  dateOfBirth: z.string(),
  address: z.object({
    city: z.string().default(""),
    country: z.string().default(""),
    countryCode: z.string().default(""),
    zipCode: z.string().default(""),
    streetAddress: z.string().default(""),
  }),
  password: passwordValidator("Password is required"),
})

export const registerUser = serviceServerActionProcedure
  .input(signUpSchema)
  .mutation(async function ({ ctx, input }) {
    const payload = {
      ...input,
      language: ctx.lang,
      phoneNumber: input.phoneNumber.replace(/\s+/g, ""),
    }

    const parsedPayload = registerUserPayload.safeParse(payload)
    if (!parsedPayload.success) {
      console.error(
        "registerUser payload validation error",
        JSON.stringify({
          query: input,
          error: parsedPayload.error,
        })
      )

      return { success: false, error: "Validation error" }
    }

    let apiResponse
    try {
      apiResponse = await api.post(api.endpoints.v1.Profile.profile, {
        body: parsedPayload.data,
        headers: {
          Authorization: `Bearer ${ctx.serviceToken}`,
        },
      })
    } catch (error) {
      console.error("Unexpected error", error)
      return { success: false, error: "Unexpected error" }
    }

    if (!apiResponse.ok) {
      const text = await apiResponse.text()
      console.error(
        "registerUser api error",
        JSON.stringify({
          query: input,
          error: {
            status: apiResponse.status,
            statusText: apiResponse.statusText,
            error: text,
          },
        })
      )
      return { success: false, error: "API error" }
    }

    const json = await apiResponse.json()
    console.log("registerUser: json", json)

    // Note: The redirect needs to be called after the try/catch block.
    // See: https://nextjs.org/docs/app/api-reference/functions/redirect
    redirect(signupVerify[ctx.lang])
  })
