"use server";

import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
import {
  clearCustomerToken,
  createCustomerAddress,
  deleteCustomerAccount,
  deleteCustomerAddress,
  loginCustomer,
  registerCustomer,
  updateCustomerProfile,
} from "@/lib/medusa/customer";
import { normalizeAuthRedirect } from "@/lib/auth-redirect";

function normalize(value: FormDataEntryValue | null) {
  return String(value || "").trim();
}

function buildAuthNoticePath(pathname: "/connexion" | "/inscription", notice: string, next: string) {
  const params = new URLSearchParams({ notice });

  if (next !== "/compte") {
    params.set("next", next);
  }

  return `${pathname}?${params.toString()}`;
}

export async function loginCustomerAction(formData: FormData) {
  const email = normalize(formData.get("email")).toLowerCase();
  const password = normalize(formData.get("password"));
  const next = normalizeAuthRedirect(normalize(formData.get("next")));

  if (!email || !password) {
    redirect(buildAuthNoticePath("/connexion", "login-missing", next));
  }

  try {
    await loginCustomer(email, password);
    revalidatePath("/compte");
    redirect(next);
  } catch {
    redirect(buildAuthNoticePath("/connexion", "login-error", next));
  }
}

export async function registerCustomerAction(formData: FormData) {
  const email = normalize(formData.get("email")).toLowerCase();
  const password = normalize(formData.get("password"));
  const firstName = normalize(formData.get("firstName"));
  const lastName = normalize(formData.get("lastName"));
  const phone = normalize(formData.get("phone"));
  const acceptedTerms = Boolean(formData.get("acceptedTerms"));
  const next = normalizeAuthRedirect(normalize(formData.get("next")));

  if (!email || password.length < 8) {
    redirect(buildAuthNoticePath("/inscription", "register-invalid", next));
  }

  if (!acceptedTerms) {
    redirect(buildAuthNoticePath("/inscription", "register-terms", next));
  }

  try {
    await registerCustomer({ email, password, firstName, lastName, phone });
    revalidatePath("/compte");
    redirect(next);
  } catch {
    redirect(buildAuthNoticePath("/inscription", "register-error", next));
  }
}

export async function logoutCustomerAction() {
  await clearCustomerToken();
  revalidatePath("/compte");
  redirect("/connexion?notice=logout-success");
}

export async function deleteCustomerAccountAction(formData: FormData) {
  if (!formData.get("deleteAccountConfirmation")) {
    redirect("/compte?notice=account-delete-error");
  }

  try {
    await deleteCustomerAccount();
    await clearCustomerToken();
    revalidatePath("/compte");
    redirect("/connexion?notice=account-deleted");
  } catch {
    redirect("/compte?notice=account-delete-error");
  }
}

export async function updateCustomerProfileAction(formData: FormData) {
  try {
    await updateCustomerProfile({
      firstName: normalize(formData.get("firstName")),
      lastName: normalize(formData.get("lastName")),
      phone: normalize(formData.get("phone")),
    });
    revalidatePath("/compte");
    redirect("/compte?notice=profile-updated");
  } catch {
    redirect("/compte?notice=profile-error");
  }
}

export async function createCustomerAddressAction(formData: FormData) {
  const address1 = normalize(formData.get("address1"));
  const city = normalize(formData.get("city"));
  const postalCode = normalize(formData.get("postalCode"));
  const countryCode = normalize(formData.get("countryCode"));

  if (!address1 || !city || !postalCode || countryCode.length !== 2) {
    redirect("/compte?notice=address-invalid");
  }

  try {
    await createCustomerAddress({
      firstName: normalize(formData.get("firstName")),
      lastName: normalize(formData.get("lastName")),
      company: normalize(formData.get("company")),
      address1,
      address2: normalize(formData.get("address2")),
      city,
      province: normalize(formData.get("province")),
      postalCode,
      countryCode,
      phone: normalize(formData.get("phone")),
      isDefaultShipping: Boolean(formData.get("isDefaultShipping")),
      isDefaultBilling: Boolean(formData.get("isDefaultBilling")),
    });
    revalidatePath("/compte");
    redirect("/compte?notice=address-added");
  } catch {
    redirect("/compte?notice=address-error");
  }
}

export async function deleteCustomerAddressAction(formData: FormData) {
  const addressId = normalize(formData.get("addressId"));

  if (!addressId) {
    redirect("/compte?notice=address-error");
  }

  try {
    await deleteCustomerAddress(addressId);
    revalidatePath("/compte");
    redirect("/compte?notice=address-deleted");
  } catch {
    redirect("/compte?notice=address-error");
  }
}
