import {
  db,
  type TailorAnyDBField,
  type TailorAnyDBType,
  unsafeAllowAllGqlPermission,
  unsafeAllowAllTypePermission,
} from "@tailor-platform/sdk";
import { company as companyStub } from "../lib/_db_deps";
import { accountingPeriod } from "./accountingPeriod";

export const JOURNAL_ENTRY_STATUSES: [string, string, string] = ["DRAFT", "POSTED", "REVERSED"];

export const JOURNAL_TYPES: [
  string,
  string,
  string,
  string,
  string,
  string,
  string,
  string,
  string,
] = [
  "SALES",
  "PURCHASE",
  "CASH",
  "BANK",
  "MISCELLANEOUS",
  "OPENING",
  "CLOSING",
  "INVENTORY",
  "MANUFACTURING",
];

const ADJUSTING_ENTRY_TYPES = ["ACCRUAL", "DEFERRAL", "RECLASSIFICATION"] as const;

export interface CreateJournalEntryTypeParams<F extends Record<string, TailorAnyDBField>> {
  fields?: F;
  companyType?: TailorAnyDBType;
  accountingPeriodType?: TailorAnyDBType;
}

export function createJournalEntryType<const F extends Record<string, TailorAnyDBField>>(
  params: CreateJournalEntryTypeParams<F>,
) {
  return db
    .type("JournalEntry", {
      companyId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.companyType ?? companyStub },
          backward: "journalEntries",
        })
        .description("Foreign key to Company"),
      accountingPeriodId: db
        .uuid()
        .relation({
          type: "n-1",
          toward: { type: params.accountingPeriodType ?? accountingPeriod },
          backward: "journalEntries",
        })
        .description("Foreign key to AccountingPeriod"),
      entryDate: db.date().description("Journal entry document date"),
      journalType: db
        .enum(JOURNAL_TYPES)
        .description(
          "Journal type categorizing the business origin (SALES, PURCHASE, CASH, BANK, MISCELLANEOUS, OPENING, CLOSING, INVENTORY, MANUFACTURING)",
        ),
      referenceNumber: db.string().description("Reference number unique within the company scope"),
      status: db
        .enum(JOURNAL_ENTRY_STATUSES)
        .description("Journal entry lifecycle status (DRAFT, POSTED, REVERSED)"),
      description: db
        .string({ optional: true })
        .description("Optional description of the journal entry"),
      sourceDocumentReference: db
        .string({ optional: true })
        .description("Optional source document reference (e.g. PurchaseBill:purchase-bill-1)"),
      adjustingEntryType: db
        .enum([...ADJUSTING_ENTRY_TYPES], { optional: true })
        .description(
          "Optional adjusting entry type for period-end adjustments (ACCRUAL, DEFERRAL, RECLASSIFICATION)",
        ),
      reversalOfId: db
        .uuid({ optional: true })
        .relation({
          type: "n-1",
          toward: { type: "self" },
          backward: "reversals",
        })
        .description("Optional self-referencing FK to the original JournalEntry being reversed"),
      postedAt: db.datetime({ optional: true }).description("Timestamp when the entry was posted"),
      ...((params.fields ?? {}) as F),
      ...db.fields.timestamps(),
    })
    .permission(unsafeAllowAllTypePermission)
    .gqlPermission(unsafeAllowAllGqlPermission);
}

export const journalEntry = createJournalEntryType({});
