import { dealTypeCaps, type DealType } from '@/lib/deal-types';
import type { OrderLineId, VendorId } from '@/server/platform-seams/ids.js';
import type { SettlementReleaseEffect } from './effects.js';

export type SettlementReleaseCtxId = string & { readonly __brand: 'SettlementReleaseCtxId' };

export const asSettlementReleaseCtxId = (value: string): SettlementReleaseCtxId =>
  value as SettlementReleaseCtxId;

export interface SettlementReleaseContext {
  ctxId: SettlementReleaseCtxId;
  paymentIntentId: string;
  chargeId: string;
  transferId: string;
  purchaseIds: OrderLineId[];
  vendorId: VendorId;
  vendorAcctId: string;
  netAmountAgorot: number;
  applicationFeeAgorot: number;
  dealType: DealType;
  holdFloorDays: number;
  heldAt: Date;
}

export interface DecideResult {
  ok: true;
  effects: SettlementReleaseEffect[];
}

export function computeReleaseAt(dealType: DealType, heldAt: Date, holdFloorDays: number): Date {
  if (dealTypeCaps(dealType).settlementHold === 'perpetual') {
    return new Date('2099-12-31T00:00:00Z');
  }
  const d = new Date(heldAt.getTime());
  d.setDate(d.getDate() + holdFloorDays);
  return d;
}

export function triggerReasonFor(dealType: DealType): string {
  return dealTypeCaps(dealType).settlementTrigger;
}

export function decide(ctx: SettlementReleaseContext): DecideResult {
  if (ctx.purchaseIds.length === 0) {
    return { ok: true, effects: [] };
  }

  return {
    ok: true,
    effects: [
      {
        kind: 'record-held-release',
        paymentIntentId: ctx.paymentIntentId,
        chargeId: ctx.chargeId,
        transferId: ctx.transferId,
        purchaseIds: ctx.purchaseIds,
        vendorId: ctx.vendorId,
        vendorAcctId: ctx.vendorAcctId,
        netAmountAgorot: ctx.netAmountAgorot,
        applicationFeeAgorot: ctx.applicationFeeAgorot,
        triggerReason: triggerReasonFor(ctx.dealType),
        heldAt: ctx.heldAt,
        releaseAt: computeReleaseAt(ctx.dealType, ctx.heldAt, ctx.holdFloorDays),
      },
    ],
  };
}
