import type {
  DesignRequestInitiateParams,
  DesignerRequestFormValues,
} from "@/pages/designer/types/Types";
import * as Yup from "yup";

const parseEnvNumber = (value: string | undefined, fallback: number): number => {
  const parsed = Number(value);
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
};

type DesignPriceTier = {
  maxPages: number;
  pricePerPage: number;
};

const DESIGN_PRICE_TIERS: DesignPriceTier[] = [
  {
    maxPages: parseEnvNumber(import.meta.env.VITE_DESIGN_TIER_1_MAX, 10),
    pricePerPage: parseEnvNumber(import.meta.env.VITE_DESIGN_PRICE_TIER_1, 700_000),
  },
  {
    maxPages: parseEnvNumber(import.meta.env.VITE_DESIGN_TIER_2_MAX, 30),
    pricePerPage: parseEnvNumber(import.meta.env.VITE_DESIGN_PRICE_TIER_2, 500_000),
  },
  {
    maxPages: parseEnvNumber(import.meta.env.VITE_DESIGN_TIER_3_MAX, 70),
    pricePerPage: parseEnvNumber(import.meta.env.VITE_DESIGN_PRICE_TIER_3, 400_000),
  },
];

const DESIGN_PRICE_TIER_4 = parseEnvNumber(
  import.meta.env.VITE_DESIGN_PRICE_TIER_4,
  350_000,
);

export const getPricePerPage = (count: number): number => {
  const tier = DESIGN_PRICE_TIERS.find((item) => count <= item.maxPages);
  return tier?.pricePerPage ?? DESIGN_PRICE_TIER_4;
};

export const designerRequestInitialValues: DesignerRequestFormValues = {
  title: "",
  count: "",
  desc: "",
  expectedDate: "",
  attachments: [],
};

export const designerRequestValidationSchema = Yup.object({
  title: Yup.string().trim().required("عنوان کاتالوگ الزامی است"),
  count: Yup.number()
    .transform((value, originalValue) =>
      originalValue === "" ? undefined : value,
    )
    .optional()
    .min(1, "حداقل تعداد صفحات ۱ است"),
  desc: Yup.string().trim(),
  expectedDate: Yup.string().required("زمان تحویل الزامی است"),
  attachments: Yup.array(),
});

export const getTotalPrice = (count: DesignerRequestFormValues["count"]) => {
  if (count === "" || count < 1) return 0;
  return count * getPricePerPage(count);
};

export const toDesignRequestParams = (
  values: DesignerRequestFormValues,
  attachmentUrls: string[],
): DesignRequestInitiateParams => {
  const { attachments: _attachments, count, ...rest } = values;

  return {
    ...rest,
    count: count === "" ? undefined : count,
    attachments: attachmentUrls,
  };
};
