"use client";
import { jsx } from "react/jsx-runtime";
import * as React from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { createCrud } from "@open-mercato/ui/backend/utils/crud";
import { createCrudFormError } from "@open-mercato/ui/backend/utils/serverErrors";
import { E } from "../../../../../../generated/entities.ids.generated.js";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useOrganizationScopeDetail } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
import {
  buildCompanyPayload,
  createCompanyFormFields,
  createCompanyFormGroups,
  createCompanyFormSchema
} from "../../../../components/formConfig.js";
function CreateCompanyPage() {
  const t = useT();
  const router = useRouter();
  const searchParams = useSearchParams();
  const { organizationId } = useOrganizationScopeDetail();
  const formSchema = React.useMemo(() => createCompanyFormSchema(), []);
  const fields = React.useMemo(() => createCompanyFormFields(t), [t]);
  const groups = React.useMemo(() => createCompanyFormGroups(t), [t]);
  const returnTo = searchParams.get("returnTo");
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
    CrudForm,
    {
      title: t("customers.companies.create.title"),
      backHref: returnTo ?? "/backend/customers/companies",
      fields,
      groups,
      initialValues: { addresses: [] },
      entityIds: [E.customers.customer_entity, E.customers.customer_company_profile],
      submitLabel: t("customers.companies.form.submit"),
      cancelHref: returnTo ?? "/backend/customers/companies",
      schema: formSchema,
      onSubmit: async (values) => {
        const addresses = Array.isArray(values.addresses) ? values.addresses : [];
        let payload;
        try {
          payload = buildCompanyPayload(values, organizationId);
        } catch (err) {
          if (err instanceof Error) {
            if (err.message === "DISPLAY_NAME_REQUIRED") {
              const message = t("customers.companies.form.displayName.error");
              throw createCrudFormError(message, { displayName: message });
            }
            if (err.message === "ANNUAL_REVENUE_INVALID") {
              const message = t("customers.companies.form.annualRevenue.error");
              throw createCrudFormError(message, { annualRevenue: message });
            }
          }
          throw err;
        }
        const { result: created } = await createCrud(
          "customers/companies",
          payload
        );
        const newId = created && typeof created.id === "string" ? created.id : typeof created?.entityId === "string" ? created.entityId : null;
        if (newId && addresses.length) {
          const normalize = (value) => {
            if (typeof value !== "string") return void 0;
            const trimmed = value.trim();
            return trimmed.length ? trimmed : void 0;
          };
          for (const entry of addresses) {
            const normalizedLine1 = normalize(entry.addressLine1);
            if (!normalizedLine1) continue;
            const body = {
              entityId: newId,
              ...organizationId ? { organizationId } : {},
              addressLine1: normalizedLine1,
              isPrimary: entry.isPrimary ?? false
            };
            const name = normalize(entry.name);
            if (name !== void 0) body.name = name;
            const purpose = normalize(entry.purpose);
            if (purpose !== void 0) body.purpose = purpose;
            const line2 = normalize(entry.addressLine2);
            if (line2 !== void 0) body.addressLine2 = line2;
            const buildingNumber = normalize(entry.buildingNumber);
            if (buildingNumber !== void 0) body.buildingNumber = buildingNumber;
            const flatNumber = normalize(entry.flatNumber);
            if (flatNumber !== void 0) body.flatNumber = flatNumber;
            const city = normalize(entry.city);
            if (city !== void 0) body.city = city;
            const region = normalize(entry.region);
            if (region !== void 0) body.region = region;
            const postalCode = normalize(entry.postalCode);
            if (postalCode !== void 0) body.postalCode = postalCode;
            const country = normalize(entry.country);
            if (country !== void 0) body.country = country.toUpperCase();
            if (typeof entry.latitude === "number") body.latitude = entry.latitude;
            if (typeof entry.longitude === "number") body.longitude = entry.longitude;
            try {
              await createCrud("customers/addresses", body);
            } catch (addressErr) {
              const message = addressErr instanceof Error && addressErr.message ? addressErr.message : t("customers.companies.detail.addresses.error");
              flash(message, "error");
            }
          }
        }
        flash(t("customers.companies.form.success"), "success");
        if (returnTo) router.push(returnTo);
        else if (newId) router.push(`/backend/customers/companies-v2/${newId}`);
        else router.push("/backend/customers/companies");
      }
    }
  ) }) });
}
export {
  CreateCompanyPage as default
};
//# sourceMappingURL=page.js.map
