/**
 * VendorDeal pure decider.
 *
 * PURITY CONTRACT (enforced by _purity-check.sh vendor-deal):
 *   - No imports from '@/server/db'
 *   - No imports from 'do-client'
 *   - No imports from 'outbox-producer'
 *   - No imports from '@/server/payments'
 *   - No imports from '@/server/storage'
 *   - No imports from '@/server/email'
 *   - No imports from '@/server/push'
 *   - No Date.now() calls (caller provides `at` via event)
 *   - No crypto.randomUUID() (caller supplies any ids)
 *
 * Transition table:
 *
 *   DRAFT       + create_requested(VETERAN)        → ACTIVE
 *     effects: [set-deal-state(ACTIVE, contentHash, approvedAt, approvedBy=AI_AGENT),
 *               arm-deal-alarm?]
 *
 *   DRAFT       + create_requested(NEW)            → UNDER_REVIEW
 *     effects: [set-deal-state(UNDER_REVIEW, contentHash), enqueue-llm-job]
 *
 *   ACTIVE      + pause_requested                  → PAUSED
 *     effects: [set-deal-state(PAUSED)]
 *
 *   PAUSED      + resume_requested                 → ACTIVE
 *     effects: [set-deal-state(ACTIVE)]
 *
 *   ACTIVE|PAUSED + archive_requested              → ARCHIVED
 *     effects: [set-deal-state(ARCHIVED)]
 *
 *   REJECTED    + submit_requested                 → UNDER_REVIEW
 *     effects: [set-deal-state(UNDER_REVIEW)]
 *
 * Non-state-machine work (zod validation, vendor lookup, content hash compute,
 * dedup query, discount-min lookup, deal row INSERT, image INSERT,
 * audit-row INSERT, locked-fields check) stays in the workflow orchestrator.
 * The decider runs AFTER the DRAFT row exists.
 */

import type { VendorDealEvent, DealState } from './events.js';
import type { VendorDealEffect } from './effects.js';

// ─── State type ───────────────────────────────────────────────────────────────

export type VendorDealState = DealState;

// ─── Context ─────────────────────────────────────────────────────────────────

export interface VendorDealContext {
  state: VendorDealState;
}

// ─── Result type ─────────────────────────────────────────────────────────────

export type DecideResult =
  | {
      ok: true;
      nextState: VendorDealState;
      effects: VendorDealEffect[];
    }
  | {
      ok: false;
      error: 'INVALID_STATE';
      from: VendorDealState;
      message: string;
    };

// ─── Decider ─────────────────────────────────────────────────────────────────

export function decide(ctx: VendorDealContext, event: VendorDealEvent): DecideResult {
  switch (event.kind) {
    case 'create_requested': {
      if (ctx.state !== 'DRAFT') {
        return {
          ok: false,
          error: 'INVALID_STATE',
          from: ctx.state,
          message: `create_requested only valid from DRAFT, got ${ctx.state}`,
        };
      }

      const isVeteran = event.vendorTier === 'VETERAN';
      const nextState: VendorDealState = isVeteran ? 'ACTIVE' : 'UNDER_REVIEW';

      const effects: VendorDealEffect[] = [
        {
          kind: 'set-deal-state',
          dealId: event.dealId,
          nextState,
          contentHash: event.contentHash,
          ...(isVeteran ? { approvedAt: event.at, approvedBy: 'AI_AGENT' } : {}),
        },
      ];

      if (isVeteran) {
        if (event.windowEnd !== null) {
          effects.push({
            kind: 'arm-deal-alarm',
            dealId: event.dealId,
            windowEnd: event.windowEnd,
          });
        }
      } else {
        effects.push({
          kind: 'enqueue-llm-job',
          dealId: event.dealId,
          vendorId: event.vendorId,
          inputs: event.llmInputs,
        });
      }

      return { ok: true, nextState, effects };
    }

    case 'pause_requested': {
      if (ctx.state !== 'ACTIVE') {
        return {
          ok: false,
          error: 'INVALID_STATE',
          from: ctx.state,
          message: `Cannot pause a deal in state ${ctx.state}`,
        };
      }
      return {
        ok: true,
        nextState: 'PAUSED',
        effects: [{ kind: 'set-deal-state', dealId: event.dealId, nextState: 'PAUSED' }],
      };
    }

    case 'resume_requested': {
      if (ctx.state !== 'PAUSED') {
        return {
          ok: false,
          error: 'INVALID_STATE',
          from: ctx.state,
          message: `Cannot resume a deal in state ${ctx.state}`,
        };
      }
      return {
        ok: true,
        nextState: 'ACTIVE',
        effects: [{ kind: 'set-deal-state', dealId: event.dealId, nextState: 'ACTIVE' }],
      };
    }

    case 'archive_requested': {
      if (ctx.state !== 'ACTIVE' && ctx.state !== 'PAUSED') {
        return {
          ok: false,
          error: 'INVALID_STATE',
          from: ctx.state,
          message: `Cannot archive a deal in state ${ctx.state}`,
        };
      }
      return {
        ok: true,
        nextState: 'ARCHIVED',
        effects: [{ kind: 'set-deal-state', dealId: event.dealId, nextState: 'ARCHIVED' }],
      };
    }

    case 'submit_requested': {
      if (ctx.state !== 'REJECTED') {
        return {
          ok: false,
          error: 'INVALID_STATE',
          from: ctx.state,
          message: `submitForApproval only accepts REJECTED deals. Current state: ${ctx.state}`,
        };
      }
      return {
        ok: true,
        nextState: 'UNDER_REVIEW',
        effects: [{ kind: 'set-deal-state', dealId: event.dealId, nextState: 'UNDER_REVIEW' }],
      };
    }

    default: {
      const _exhaustive: never = event;
      void _exhaustive;
      return {
        ok: false,
        error: 'INVALID_STATE',
        from: ctx.state,
        message: 'Unhandled event kind',
      };
    }
  }
}
