import { z } from "zod";

export const creditCardSchema = z.object({
  bankName: z.string().trim().min(1, "Banka adı zorunlu.").max(100),
  cardName: z.string().trim().min(1, "Kart adı zorunlu.").max(100),
  last4: z
    .string()
    .trim()
    .max(4)
    .optional()
    .transform((v) => (v ? v.replace(/\D/g, "").slice(-4) : undefined)),
  creditLimit: z
    .union([z.number(), z.string()])
    .optional()
    .transform((v) => {
      if (v === undefined || v === "") return 0;
      const n = typeof v === "string" ? Number(v.replace(",", ".")) : v;
      return Number.isFinite(n) ? n : 0;
    }),
  statementDay: 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;
    }),
  dueDay: z
    .union([z.number(), z.string()])
    .optional()
    .transform((v) => {
      if (v === undefined || v === "") return 10;
      const n = typeof v === "string" ? parseInt(v, 10) : v;
      return Number.isFinite(n) ? Math.min(28, Math.max(1, n)) : 10;
    }),
  interestRate: z
    .union([z.number(), z.string()])
    .optional()
    .transform((v) => {
      if (v === undefined || v === "") return 4.25;
      const n = typeof v === "string" ? Number(v.replace(",", ".")) : v;
      return Number.isFinite(n) ? n : 4.25;
    }),
  bankAccountId: z.string().optional().transform((v) => (v ? v : undefined)),
  notes: z.string().trim().max(500).optional().transform((v) => (v ? v : undefined)),
  scope: z.enum(["company", "personal"]).optional().default("company"),
});

export type CreditCardInput = z.infer<typeof creditCardSchema>;

export const statementSchema = z.object({
  cardId: z.string().min(1, "Kart seçin."),
  period: z
    .string()
    .regex(/^\d{4}-\d{2}$/, "Dönem YYYY-AA formatında olmalı.")
    .max(7),
  statementDate: z.string().min(1, "Hesap kesim tarihi zorunlu."),
  dueDate: z.string().min(1, "Son ödeme tarihi zorunlu."),
  totalDebt: z
    .union([z.number(), z.string()])
    .transform((v) => (typeof v === "string" ? Number(v.replace(",", ".")) : v))
    .pipe(z.number().nonnegative("Negatif olamaz.")),
  minimumPayment: z
    .union([z.number(), z.string()])
    .optional()
    .transform((v) => {
      if (v === undefined || v === "") return 0;
      const n = typeof v === "string" ? Number(v.replace(",", ".")) : v;
      return Number.isFinite(n) ? n : 0;
    }),
  notes: z.string().trim().max(500).optional().transform((v) => (v ? v : undefined)),
});

export type StatementInput = z.infer<typeof statementSchema>;
