/* Shared validation for the institution's collection accounts. */

const TYPES = ["MOBILE", "BANK", "OTHER"];
const PROVIDERS = ["BKASH", "NAGAD", "ROCKET", "UPAY", "OTHER"];

export type CollectionAccountData = {
  type: string;
  provider: string | null;
  accountType: string | null;
  label: string;
  accountName: string | null;
  accountNumber: string;
  branch: string | null;
  routingNo: string | null;
  note: string | null;
  isActive: boolean;
  sortOrder: number;
};

export function sanitizeCollectionAccount(body: Record<string, unknown>):
  | { error: "Invalid type" | "ACCOUNT_NUMBER_REQUIRED" | "LABEL_REQUIRED" }
  | { data: CollectionAccountData } {
  const str = (v: unknown) => (typeof v === "string" ? v.trim() : "");
  const type = TYPES.includes(String(body.type)) ? String(body.type) : null;
  if (!type) return { error: "Invalid type" };
  const accountNumber = str(body.accountNumber) || (type === "OTHER" ? "—" : "");
  const label =
    str(body.label) ||
    (type === "MOBILE" && PROVIDERS.includes(str(body.provider)) && str(body.provider) !== "OTHER"
      ? str(body.provider)
      : "");
  if (!accountNumber) return { error: "ACCOUNT_NUMBER_REQUIRED" };
  if (type !== "OTHER" && !label) return { error: "LABEL_REQUIRED" };
  return {
    data: {
      type,
      provider: type === "MOBILE" && PROVIDERS.includes(str(body.provider)) ? str(body.provider) : null,
      accountType: type === "MOBILE" && ["PERSONAL", "MERCHANT"].includes(str(body.accountType)) ? str(body.accountType) : null,
      label: label || str(body.label),
      accountName: str(body.accountName) || null,
      accountNumber,
      branch: str(body.branch) || null,
      routingNo: str(body.routingNo) || null,
      note: str(body.note) || null,
      isActive: body.isActive !== false,
      sortOrder: Number(body.sortOrder) || 0,
    },
  };
}
