import { z } from "zod";
import { loyaltyApi } from "@/modules/loyalty/services/loyalty-api";
import { createLoyaltyListPage } from "@/modules/loyalty/components/LoyaltyListCrudPage";
import { LoyaltyStatusChip } from "@/modules/loyalty/design-system";
import type { LoyaltyProgram } from "@/modules/loyalty/types";

const createSchema = z.object({
  code: z.string().min(1, "کد الزامی است"),
  name: z.string().min(1, "نام الزامی است"),
  description: z.string().optional(),
  status: z.enum(["draft", "active", "suspended", "archived"]).default("draft"),
  points_currency_name: z.string().default("points"),
  currency_code: z.string().default("IRR"),
  is_default: z.coerce.boolean().default(false),
});

const editSchema = createSchema.partial().extend({
  version: z.coerce.number().optional(),
});

export default createLoyaltyListPage<LoyaltyProgram>({
  title: "برنامه‌های وفاداری",
  description: "مدیریت برنامه‌های عضویت — ایجاد، ویرایش و حذف نرم.",
  breadcrumb: "برنامه‌ها",
  resourceKey: "programs",
  createSchema,
  editSchema,
  createDefaults: {
    code: "",
    name: "",
    description: "",
    status: "draft",
    points_currency_name: "points",
    currency_code: "IRR",
    is_default: false,
  },
  fields: [
    { name: "code", label: "کد", required: true, createOnly: true },
    { name: "name", label: "نام", required: true },
    { name: "description", label: "توضیحات", type: "textarea" },
    {
      name: "status",
      label: "وضعیت",
      type: "select",
      options: [
        { value: "draft", label: "پیش‌نویس" },
        { value: "active", label: "فعال" },
        { value: "suspended", label: "معلق" },
        { value: "archived", label: "آرشیو" },
      ],
    },
    { name: "points_currency_name", label: "نام واحد امتیاز" },
    { name: "currency_code", label: "ارز" },
  ],
  columns: [
    { key: "code", header: "کد" },
    { key: "name", header: "نام" },
    {
      key: "status",
      header: "وضعیت",
      render: (r) => <LoyaltyStatusChip status={r.status} domain="program" />,
    },
    { key: "points_currency_name", header: "امتیاز" },
    { key: "currency_code", header: "ارز" },
  ],
  list: (tid) => loyaltyApi.programs.list(tid, { page: 1, page_size: 500 }),
  create: (tid, d) => loyaltyApi.programs.create(tid, d),
  update: (tid, id, d) => loyaltyApi.programs.update(tid, id, d),
  remove: (tid, id) => loyaltyApi.programs.delete(tid, id),
  filterDeleted: true,
  exportColumns: ["code", "name", "status", "points_currency_name", "currency_code"],
});
