import { z } from "zod";

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

export const paymentSchema = z.object({
  counterpartTenantId: z.string().min(1, "Karşı taraf seçin."),
  amount: z
    .union([z.string(), z.number()])
    .transform(toNumber)
    .pipe(z.number().positive("Tutar 0'dan büyük olmalı.")),
  currency: z
    .string()
    .trim()
    .max(8)
    .optional()
    .transform((v) => (v ? v.toUpperCase() : "TRY")),
  paymentDate: z
    .string()
    .trim()
    .optional()
    .transform((v) => (v ? new Date(v).toISOString() : new Date().toISOString())),
  method: z
    .string()
    .trim()
    .max(30)
    .optional()
    .transform((v) => (v ? v : undefined)),
  notes: z
    .string()
    .trim()
    .max(1000)
    .optional()
    .transform((v) => (v ? v : undefined)),
});

export type PaymentInput = z.infer<typeof paymentSchema>;
