import { z } from "zod";

export const bankLoanSchema = z.object({
  bankAccountId: z.string().optional().transform((v) => (v ? v : undefined)),
  bankName: z.string().trim().min(1, "Banka adı zorunlu.").max(100),
  loanName: z.string().trim().min(1, "Kredi adı zorunlu.").max(150),
  loanType: z
    .enum(["consumer", "vehicle", "housing", "commercial", "kmh", "other"])
    .optional()
    .default("consumer"),
  principal: z
    .union([z.number(), z.string()])
    .transform((v) => (typeof v === "string" ? Number(v.replace(",", ".")) : v))
    .pipe(z.number().positive("Anapara 0'dan büyük olmalı.")),
  interestRate: z
    .union([z.number(), z.string()])
    .transform((v) => (typeof v === "string" ? Number(v.replace(",", ".")) : v))
    .pipe(z.number().min(0, "Negatif olamaz.").max(100, "100'den büyük olamaz.")),
  termMonths: z
    .union([z.number(), z.string()])
    .transform((v) => (typeof v === "string" ? parseInt(v, 10) : v))
    .pipe(z.number().int().positive("Vade pozitif olmalı.").max(480, "Çok uzun.")),
  startDate: z.string().min(1, "Başlangıç tarihi zorunlu."),
  paymentDay: z
    .union([z.number(), z.string()])
    .optional()
    .transform((v) => {
      if (v === undefined || v === "") return 1;
      const n = typeof v === "string" ? parseInt(v, 10) : v;
      return Number.isFinite(n) ? Math.min(28, Math.max(1, n)) : 1;
    }),
  notes: z.string().trim().max(1000).optional().transform((v) => (v ? v : undefined)),
  scope: z.enum(["company", "personal"]).optional().default("company"),
});

export type BankLoanInput = z.infer<typeof bankLoanSchema>;
