import type { Currency, Deposit, Invoice, InvoiceLine, MaintenanceRequest, MaintenanceTask, MeterReading, Prisma, Receipt } from '@prisma/client';
import type { ReadingHold } from '../metering/metering.service';
import type {
  ArAging,
  Collections,
  Dashboard,
  IncomeStatement,
  OutstandingInvoiceQuery,
  OutstandingInvoices,
  RentRoll,
  StatementQuery,
  Statements,
  TrialBalance,
} from '../reports/reports.types';
import type { SentStatementRow } from '../statements/statements.service';

/** Application services exposed to tRPC procedures via the context, as
 * dependency-free interfaces so the router types stay importable by the client. */

export type InvoiceWithLines = Invoice & { lines: InvoiceLine[] };

export interface BillingPort {
  generateDraft(input: {
    organizationId: string;
    leaseId: string;
    period: string;
    unitIds?: string[];
  }): Promise<InvoiceWithLines>;
  /** `number` is one the office typed; none takes the next in sequence. */
  issue(input: { organizationId: string; invoiceId: string; issuedByUserId?: string | null; number?: string | null }): Promise<InvoiceWithLines>;
  setSchedule(input: { organizationId: string; invoiceId: string; date: Date | null }): Promise<InvoiceWithLines>;
  submitForApproval(input: {
    organizationId: string;
    invoiceId: string;
  }): Promise<{ workflowName: string; totalSteps: number }>;
  approvalState(input: {
    organizationId: string;
    invoiceId: string;
    userId: string;
  }): Promise<ApprovalDocumentState>;
  generateDraftsForPeriod(input: {
    organizationId: string;
    period: string;
  }): Promise<{ created: number; skipped: number; leaseCount: number }>;
  generateGroupDrafts(input: { organizationId: string; leaseId: string; period: string }): Promise<{ created: number; skipped: number }>;
  transitionLeases(input: {
    organizationId: string;
    asOf: Date;
  }): Promise<{ activated: number; ended: number; depositsMoved: number }>;
  terminateLease(input: {
    organizationId: string;
    leaseId: string;
    terminationDate: Date;
    reason?: string | null;
  }): Promise<{
    leaseId: string;
    finalInvoiceId: string | null;
    finalInvoiceSkipped: 'ALREADY_BILLED' | 'NOTHING_TO_BILL' | null;
  }>;
  leaseOpenInvoices(
    organizationId: string,
    leaseId: string,
  ): Promise<{
    id: string;
    number: string | null;
    billingPeriod: string;
    status: string;
    currency: string;
    outstanding: string;
  }[]>;
  carryForward(input: {
    organizationId: string;
    invoiceId: string;
    targetPeriod?: string;
    carriedByUserId?: string | null;
  }): Promise<InvoiceWithLines>;
  voidInvoice(input: { organizationId: string; invoiceId: string }): Promise<InvoiceWithLines>;
  regenerateDraft(input: {
    organizationId: string;
    invoiceId: string;
  }): Promise<{ replaced: number; kept: number; total: string }>;
  addAdjustment(input: {
    organizationId: string;
    invoiceId: string;
    chargeTypeId: string;
    description: string;
    amount: string;
    credit: boolean;
  }): Promise<void>;
  waiveInterest(input: { organizationId: string; invoiceId: string }): Promise<{ removed: number }>;
  removeLine(input: { organizationId: string; lineId: string }): Promise<void>;
  unwindCarryForward(input: { organizationId: string; lineId: string; reversedByUserId?: string | null }): Promise<void>;
}

export interface OpenInvoice {
  id: string;
  number: string | null;
  billingPeriod: string;
  dueDate: Date;
  currency: Currency;
  outstanding: string;
}

export interface PaymentsPort {
  submitReceipt(input: {
    organizationId: string;
    tenantId: string;
    invoiceId: string;
    amount: string;
    settlementMethodId?: string | null;
    reference?: string | null;
    uploadedByUserId?: string | null;
  }): Promise<Receipt>;
  recordBulkPayment(input: {
    organizationId: string;
    tenantId: string;
    amount: string;
    settlementMethodId?: string | null;
    reference?: string | null;
    receivedDate?: Date;
    note?: string | null;
    uploadedByUserId?: string | null;
    allocations: { invoiceId: string; amount: string }[];
    number?: string | null;
    /** The part paid over what the notes owe, held for one of the tenant's leases. */
    overpayment?: { amount: string; leaseId: string } | null;
  }): Promise<Receipt>;
  /** Money for a lease before its debit note exists — a Deposit Receipt. */
  recordDepositReceipt(input: {
    organizationId: string;
    tenantId: string;
    leaseId: string;
    amount: string;
    settlementMethodId?: string | null;
    reference?: string | null;
    receivedDate?: Date;
    note?: string | null;
    uploadedByUserId?: string | null;
    number?: string | null;
  }): Promise<Receipt>;
  /** Takes one drawing of a deposit receipt back off its note. */
  withdrawCredit(input: { organizationId: string; allocationId: string; userId?: string | null }): Promise<{ invoiceId: string }>;
  approve(input: { organizationId: string; receiptId: string; reviewedByUserId?: string | null }): Promise<Receipt>;
  reject(input: { organizationId: string; receiptId: string; reason?: string | null; reviewedByUserId?: string | null }): Promise<Receipt>;
  bounce(input: { organizationId: string; receiptId: string; reason?: string | null; reviewedByUserId?: string | null }): Promise<Receipt>;
  listOpenInvoices(organizationId: string, tenantId: string): Promise<OpenInvoice[]>;
}

export interface DepositSettlementData {
  depositNumber: string;
  tenantName: string;
  leaseId: string | null;
  leaseRef: string | null;
  status: string;
  held: string;
  outstandingInvoices: { id: string; number: string | null; billingPeriod: string; outstanding: string }[];
  chargeTypes: { id: string; nameEn: string }[];
}

export interface DepositSettlementStatement {
  depositNumber: string;
  currency: Currency;
  tenantName: string;
  tenantNameZh: string | null;
  leaseRef: string | null;
  heldAmount: string;
  refundAmount: string;
  note: string | null;
  createdAt: Date;
  refundedAt: Date | null;
  refundMethodEn: string | null;
  refundMethodZh: string | null;
  refundReference: string | null;
  lines: { kind: string; description: string; amount: string }[];
}

/** What the refund-approval panel needs. `required: false` means no workflow
 *  applies at this amount, so the payout is not gated at all. */
export interface DepositRefundApprovalState {
  required: boolean;
  canAct: boolean;
  settlementId: string;
  refundAmount: string;
  currency: string;
  workflowName: string;
  totalSteps: number;
  current: {
    instanceId: string;
    round: number;
    workflowName: string;
    currentStep: number;
    totalSteps: number;
    stepName: string | null;
  } | null;
  rounds: {
    round: number;
    workflowName: string;
    status: string;
    createdAt: Date;
    actions: { stepOrder: number; stepName: string | null; action: string; actorName: string | null; note: string | null; actedAt: Date }[];
  }[];
}

export interface DepositsPort {
  create(input: {
    organizationId: string;
    tenantId: string;
    leaseId?: string | null;
    amount: string;
    receivedDate?: string | null;
    receivedByUserId?: string | null;
    number?: string | null;
  }): Promise<Deposit>;
  apply(input: { organizationId: string; depositId: string; invoiceId: string; amount: string; appliedByUserId?: string | null }): Promise<Deposit>;
  unapply(input: { organizationId: string; allocationId: string; reversedByUserId?: string | null }): Promise<void>;
  /** Read-only: never opens a round, so a clerk can be told before acting. */
  refundApprovalState(organizationId: string, depositId: string, userId: string): Promise<DepositRefundApprovalState | null>;
  submitRefundForApproval(input: { organizationId: string; depositId: string }): Promise<{ workflowName: string; totalSteps: number }>;
  settlementData(organizationId: string, depositId: string): Promise<DepositSettlementData | null>;
  getSettlement(organizationId: string, depositId: string): Promise<DepositSettlementStatement | null>;
  awaitingSettlement(organizationId: string): Promise<{
    id: string;
    number: string;
    tenantName: string;
    leaseRef: string | null;
    endDate: Date | null;
    held: string;
    currency: string;
  }[]>;
  settle(input: {
    organizationId: string;
    depositId: string;
    arrears?: { invoiceId: string; amount: string }[];
    charges?: { description: string; chargeTypeId: string; amount: string }[];
    note?: string | null;
    settledByUserId?: string | null;
  }): Promise<{ settlementId: string; refundAmount: string }>;
  heldForLease(
    organizationId: string,
    leaseId: string,
  ): Promise<{ id: string; number: string; currency: string; held: string }[]>;
  disburseRefund(input: {
    organizationId: string;
    depositId: string;
    settlementMethodId?: string | null;
    reference?: string | null;
    disbursedByUserId?: string | null;
  }): Promise<{ refundAmount: string }>;
  reverseSettlement(input: {
    organizationId: string;
    depositId: string;
    reversedByUserId?: string | null;
  }): Promise<void>;
}

export interface MeteringPort {
  createReading(input: {
    organizationId: string;
    meterId: string;
    readingStart: string;
    readingEnd: string;
    periodStart: string;
    periodEnd: string;
    note?: string | null;
  }): Promise<MeterReading>;
  updateReading(input: {
    organizationId: string;
    id: string;
    readingStart: string;
    readingEnd: string;
    periodStart: string;
    periodEnd: string;
    note?: string | null;
  }): Promise<MeterReading>;
  /** Prices the confirmed, unbilled readings still waiting for a rate on the
   *  matched meters. Call it after the caller's change has committed. */
  priceUnpriced(meters: Prisma.MeterWhereInput): Promise<void>;
  /** Sets one property's rate for a utility and prices what was waiting for it. */
  setTariff(input: { organizationId: string; chargeTypeId: string; propertyId: string; unitRate: string; fixedCharge: string }): Promise<void>;
  clearTariff(input: { organizationId: string; chargeTypeId: string; propertyId: string }): Promise<void>;
  /** Why each unbilled reading has not reached a debit note. Keyed by reading id;
   *  absent means nothing is holding it back. */
  explainUnbilled(
    organizationId: string,
    readings: readonly {
      id: string;
      meterId: string;
      periodStart: Date;
      periodEnd: Date;
      readingStart: Prisma.Decimal;
      readingEnd: Prisma.Decimal;
      grossAmount: Prisma.Decimal | null;
      status: string;
      claims: readonly { unitId: string }[];
    }[],
    asOf: Date,
  ): Promise<Map<string, ReadingHold>>;
}

export interface PendingApproval {
  instanceId: string;
  documentType: string;
  documentId: string;
  workflowName: string;
  stepName: string;
  currentStep: number;
  totalSteps: number;
  createdAt: Date;
  documentLabel: string | null;
  /** Set for DEPOSIT_REFUND, so the inbox can open what is being signed. */
  depositId: string | null;
}

/** CANCELLED = the round was invalidated by a change to the document itself. */
export type ApprovalRoundStatus = 'PENDING' | 'APPROVED' | 'REJECTED' | 'CANCELLED';

export interface ApprovalRound {
  round: number;
  workflowName: string;
  status: ApprovalRoundStatus;
  createdAt: Date;
  actions: {
    stepOrder: number;
    stepName: string | null;
    action: string;
    actorName: string | null;
    note: string | null;
    actedAt: Date;
  }[];
}

/** A document's whole approval picture: whether one is required at the current
 * amount, the live round, whether the caller may act, and every round's trail. */
export interface ApprovalDocumentState {
  required: boolean;
  canAct: boolean;
  current: {
    instanceId: string;
    round: number;
    workflowName: string;
    currentStep: number;
    totalSteps: number;
    stepName: string | null;
  } | null;
  rounds: ApprovalRound[];
}

export interface ApprovalPort {
  pending(organizationId: string, userId: string): Promise<PendingApproval[]>;
  pendingCount(organizationId: string, userId: string): Promise<number>;
  act(input: {
    organizationId: string;
    userId: string;
    instanceId: string;
    action: 'APPROVE' | 'REJECT';
    note?: string | null;
  }): Promise<{ ok: true; status: ApprovalRoundStatus }>;
}

export interface ReportsPort {
  trialBalance(organizationId: string, asOf: string): Promise<TrialBalance>;
  arAging(organizationId: string, asOf: string, tenantIds?: readonly string[]): Promise<ArAging>;
  outstandingInvoices(organizationId: string, query: OutstandingInvoiceQuery): Promise<OutstandingInvoices>;
  statements(organizationId: string, query: StatementQuery): Promise<Statements>;
  incomeStatement(organizationId: string, from: string, to: string): Promise<IncomeStatement>;
  rentRoll(organizationId: string): Promise<RentRoll>;
  collections(organizationId: string, from: string, to: string): Promise<Collections>;
  dashboard(organizationId: string, month: string): Promise<Dashboard>;
}

export interface MaintenancePort {
  create(input: {
    organizationId: string;
    propertyId: string;
    unitId?: string | null;
    tenantId?: string | null;
    leaseId?: string | null;
    categoryId?: string | null;
    priorityId?: string | null;
    title: string;
    description?: string | null;
    costResponsibility?: string | null;
    tenantSharePercent?: string | null;
    estimatedCost?: string | null;
    reportedByUserId?: string | null;
  }): Promise<MaintenanceRequest>;
  update(input: {
    organizationId: string;
    id: string;
    categoryId?: string | null;
    priorityId?: string | null;
    title?: string;
    description?: string | null;
    leaseId?: string | null;
    costResponsibility?: string | null;
    tenantSharePercent?: string | null;
    estimatedCost?: string | null;
    actualCost?: string | null;
  }): Promise<MaintenanceRequest>;
  transition(input: { organizationId: string; id: string; toStatus: string }): Promise<MaintenanceRequest>;
  addTask(input: {
    organizationId: string;
    requestId: string;
    title: string;
    assignedToId?: string | null;
    assignedVendor?: string | null;
    scheduledDate?: string | null;
    note?: string | null;
  }): Promise<MaintenanceTask>;
  updateTask(input: {
    organizationId: string;
    taskId: string;
    title?: string;
    status?: string;
    assignedToId?: string | null;
    assignedVendor?: string | null;
    scheduledDate?: string | null;
    note?: string | null;
  }): Promise<MaintenanceTask>;
  chargeToTenant(input: { organizationId: string; id: string }): Promise<{ invoiceId: string }>;
}

export interface DocumentTemplateRow {
  id: string;
  docType: string;
  name: string;
  body: string;
  pageSize: string;
  marginsMm: string;
  updatedAt: Date;
}

export interface DocumentsPort {
  template(organizationId: string, docType?: string): Promise<DocumentTemplateRow>;
  saveTemplate(input: {
    organizationId: string;
    docType: string;
    name?: string;
    body: string;
    pageSize?: string;
    marginsMm?: string;
  }): Promise<DocumentTemplateRow>;
  resetTemplate(organizationId: string, docType?: string): Promise<DocumentTemplateRow>;
}

export interface StatementsPort {
  send(input: { organizationId: string; query: StatementQuery & { leaseIds: string[] }; sentById?: string | null }): Promise<{ sent: number }>;
  withdraw(organizationId: string, id: string): Promise<void>;
  forPeriod(organizationId: string, from: string, to: string): Promise<SentStatementRow[]>;
  forTenant(tenantId: string): Promise<SentStatementRow[]>;
}
