import type { CurrencyCode, EntryType, LedgerEntry } from "@cents/domain";
import { createId } from "./ids";

type EntryInput = {
  ledgerIds: string[];
  type: EntryType;
  amount: number;
  currency: CurrencyCode;
  categoryId: string;
  note: string;
  occurredAt: string;
  createdBy?: string;
  reimbursementOfEntryId?: string | null;
};

const baseCurrency: CurrencyCode = "CNY";

export function createEntry(input: EntryInput): LedgerEntry {
  const now = new Date().toISOString();
  const exchangeRateDate = localDate(input.occurredAt);
  const isCny = input.currency === "CNY";

  return {
    id: createId(),
    ownerId: input.createdBy ?? "local-user",
    ledgerIds: [...new Set(input.ledgerIds)],
    type: input.type,
    amount: input.amount,
    currency: input.currency,
    baseCurrency,
    baseAmount: isCny ? input.amount : null,
    exchangeRate: isCny ? "1" : null,
    exchangeRateDate,
    exchangeRateEffectiveDate: isCny ? exchangeRateDate : null,
    exchangeRateSource: "system",
    conversionStatus: isCny ? "exact" : "pending",
    reimbursementOfEntryId: input.reimbursementOfEntryId ?? null,
    categoryId: input.categoryId,
    note: input.note,
    occurredAt: input.occurredAt,
    createdBy: input.createdBy ?? "local-user",
    updatedBy: input.createdBy ?? "local-user",
    createdAt: now,
    updatedAt: now,
    deletedAt: null,
    version: 1,
  };
}

export function localDate(value: string) {
  const date = new Date(value);
  const pad = (part: number) => String(part).padStart(2, "0");
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
}

export function createDemoEntries(): LedgerEntry[] {
  const now = new Date();
  const at = (daysAgo: number, hours: number, minutes: number) => {
    const date = new Date(now);
    date.setDate(date.getDate() - daysAgo);
    date.setHours(hours, minutes, 0, 0);
    return date.toISOString();
  };

  return [
    createEntry({ ledgerIds: ["local-ledger"], type: "expense", amount: 5800, currency: "CNY", categoryId: "takeout", note: "午餐", occurredAt: at(0, 12, 28) }),
    createEntry({ ledgerIds: ["local-ledger"], type: "expense", amount: 3150, currency: "CNY", categoryId: "taxi", note: "打车", occurredAt: at(0, 9, 16) }),
    createEntry({ ledgerIds: ["local-ledger"], type: "income", amount: 824000, currency: "CNY", categoryId: "salary", note: "工资", occurredAt: at(1, 18, 2) }),
    createEntry({ ledgerIds: ["local-ledger"], type: "expense", amount: 23680, currency: "CNY", categoryId: "groceries", note: "超市采购", occurredAt: at(1, 16, 45) }),
    createEntry({ ledgerIds: ["local-ledger"], type: "expense", amount: 2600, currency: "CNY", categoryId: "coffee", note: "咖啡", occurredAt: at(2, 14, 10) }),
  ];
}
