import type { PosCashSessionRepository, PosTerminalRepository } from '../domain/ports.js';
import type { PosCashSession } from '../domain/cash-session.js';
import { CashSessionAlreadyOpenError, TerminalNotBoundError, TerminalDisabledError } from '../domain/errors.js';

export interface OpenCashSessionInput {
  terminalId: string;
  userId: string;
  openingCashCents: number;
}

export class OpenCashSessionUseCase {
  constructor(
    private readonly sessionRepo: PosCashSessionRepository,
    private readonly terminalRepo: PosTerminalRepository,
  ) {}

  async execute(input: OpenCashSessionInput): Promise<PosCashSession> {
    const terminal = await this.terminalRepo.findById(input.terminalId);
    if (!terminal) throw new Error(`Terminal ${input.terminalId} not found`);
    if (terminal.status === 'disabled') throw new TerminalDisabledError(input.terminalId);
    if (!terminal.bindingCode) throw new TerminalNotBoundError(input.terminalId);

    const existing = await this.sessionRepo.findOpenByTerminal(input.terminalId);
    if (existing) throw new CashSessionAlreadyOpenError(input.terminalId);

    return this.sessionRepo.open(input);
  }
}
