import type { RegisterPayload } from "@/lib/api/types";

/** Everything the four-step sign-up form collects. */
export interface RegistrationData {
  // Step 1: Restaurant info
  name: string;
  categoryId: string;
  description: string;
  // Step 2: Owner info
  ownerName: string;
  email: string;
  phone: string;
  // Step 3: Location
  address: string;
  city: string;
  // Step 4: Account
  password: string;
  confirmPassword: string;
  agreeTerms: boolean;
}

/** Sets one field of the form. */
export type UpdateField = <K extends keyof RegistrationData>(
  key: K,
  value: RegistrationData[K]
) => void;

export const emptyRegistration: RegistrationData = {
  name: "",
  categoryId: "",
  description: "",
  ownerName: "",
  email: "",
  phone: "",
  address: "",
  city: "",
  password: "",
  confirmPassword: "",
  agreeTerms: false,
};

export const registrationSteps = [
  { label: "Restaurant", desc: "Basic info" },
  { label: "Owner", desc: "Your details" },
  { label: "Location", desc: "Address" },
  { label: "Account", desc: "Set password" },
];

export const LAST_STEP = registrationSteps.length - 1;

/** The shortest password the API accepts. */
export const MIN_PASSWORD_LENGTH = 8;

/**
 * Whether the step's required fields are filled in. A cuisine is required only
 * when the admin has created categories to choose from; none are built in.
 */
export function canProceedFrom(
  step: number,
  data: RegistrationData,
  categoryCount: number
): boolean {
  switch (step) {
    case 0:
      return Boolean(data.name && (categoryCount === 0 || data.categoryId));
    case 1:
      return Boolean(data.ownerName && data.email && data.phone);
    case 2:
      return Boolean(data.address && data.city);
    case 3:
      return (
        data.password.length >= MIN_PASSWORD_LENGTH &&
        data.password === data.confirmPassword &&
        data.agreeTerms
      );
    default:
      return false;
  }
}

/** What the register endpoint is sent. Spaces, dashes and brackets are dropped from the phone number. */
export function toRegisterPayload(data: RegistrationData): RegisterPayload {
  return {
    restaurant_name: data.name,
    category_id: data.categoryId ? Number(data.categoryId) : undefined,
    description: data.description,
    owner_name: data.ownerName,
    email: data.email,
    phone: data.phone.replace(/[\s\-().]/g, ""),
    address: data.address,
    city: data.city,
    password: data.password,
    password_confirmation: data.confirmPassword,
  };
}
