import type { PosStoreRepository, PosTerminalRepository, PosCashSessionRepository } from '../domain/ports.js';
import type { PosPaymentMethodRepository } from '../infrastructure/pg-payment-method-repository.js';
import type { PosStore } from '../domain/store.js';
import type { PosTerminal } from '../domain/terminal.js';
import type { PosPaymentMethod } from '../infrastructure/pg-payment-method-repository.js';
import type { PosCashSession } from '../domain/cash-session.js';

export interface PosConfig {
  store: PosStore;
  terminal: PosTerminal;
  paymentMethods: PosPaymentMethod[];
  sessionOpen: boolean;
  session: PosCashSession | null;
}

export class GetPosConfigUseCase {
  constructor(
    private readonly storeRepo: PosStoreRepository,
    private readonly terminalRepo: PosTerminalRepository,
    private readonly paymentMethodRepo: PosPaymentMethodRepository,
    private readonly sessionRepo: PosCashSessionRepository,
  ) {}

  async execute(terminalId: string): Promise<PosConfig> {
    const terminal = await this.terminalRepo.findById(terminalId);
    if (!terminal) throw new Error(`Terminal ${terminalId} not found`);
    const store = await this.storeRepo.findById(terminal.storeId);
    if (!store) throw new Error(`Store ${terminal.storeId} not found`);
    const [paymentMethods, openSession] = await Promise.all([
      this.paymentMethodRepo.listByStore(terminal.storeId),
      this.sessionRepo.findOpenByTerminal(terminalId),
    ]);
    await this.terminalRepo.updateLastSeen(terminalId);
    return { store, terminal, paymentMethods, sessionOpen: !!openSession, session: openSession ?? null };
  }
}
