import { z } from "zod";

const PROSTHETIC_TYPES = [
  "metal_porselen",
  "zirkonyum",
  "implant_ustu_zirkonyum",
  "gecici",
  "e_max",
  "diger",
] as const;

function toOptionalNumber(v: unknown): number | undefined {
  if (v === undefined || v === null || v === "") return undefined;
  const n = typeof v === "number" ? v : Number(String(v).replace(",", "."));
  return Number.isFinite(n) ? n : undefined;
}

export const clinicPricingSchema = z
  .object({
    clinicTenantId: z.string().min(1, "Klinik seçin."),
    prostheticType: z.enum(PROSTHETIC_TYPES, { message: "Protez türü seçin." }),
    customUnitPrice: z
      .union([z.string(), z.number(), z.literal("")])
      .optional()
      .transform(toOptionalNumber),
    discountPercent: z
      .union([z.string(), z.number(), z.literal("")])
      .optional()
      .transform(toOptionalNumber),
    currency: z
      .string()
      .trim()
      .max(8)
      .optional()
      .transform((v) => (v ? v.toUpperCase() : undefined)),
  })
  .superRefine((data, ctx) => {
    if (
      data.customUnitPrice === undefined &&
      data.discountPercent === undefined
    ) {
      ctx.addIssue({
        code: "custom",
        path: ["customUnitPrice"],
        message: "Özel fiyat veya indirim oranı girin.",
      });
    }
    if (data.discountPercent !== undefined) {
      if (data.discountPercent < 0 || data.discountPercent > 100) {
        ctx.addIssue({
          code: "custom",
          path: ["discountPercent"],
          message: "İndirim 0-100 arası olmalı.",
        });
      }
    }
    if (data.customUnitPrice !== undefined && data.customUnitPrice < 0) {
      ctx.addIssue({
        code: "custom",
        path: ["customUnitPrice"],
        message: "Negatif fiyat olamaz.",
      });
    }
  });

export type ClinicPricingInput = z.infer<typeof clinicPricingSchema>;
