import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { StandingOrderRepository } from '../../infrastructure/repositories/standing-order.repository';
import { StandingOrder } from '../../domain/entities/standing-order.entity';

export interface UpdateStandingOrderInput {
  name?: string;
  description?: string;
  lastModifiedInSessionId?: string;
  trigger?: StandingOrder['trigger'];
  targets?: StandingOrder['targets'];
  agentPrompt?: string;
  agentSkills?: string[];
  runbookId?: string;
  maxRiskLevel?: 0 | 1;
  maxTurns?: number;
  maxBudgetUsd?: number;
  decisionBoundary?: StandingOrder['decisionBoundary'];
  escalationPolicyId?: string;
  status?: 'active' | 'paused' | 'archived';
  validUntil?: Date;
}

@Injectable()
export class UpdateStandingOrderUseCase {
  private readonly logger = new Logger(UpdateStandingOrderUseCase.name);

  constructor(
    private readonly standingOrderRepository: StandingOrderRepository,
  ) {}

  async execute(orderId: string, input: UpdateStandingOrderInput): Promise<StandingOrder> {
    const order = await this.standingOrderRepository.findById(orderId);
    if (!order) {
      throw new NotFoundException(`Standing order ${orderId} not found`);
    }

    this.logger.log(`Updating standing order: ${orderId}`);

    if (input.name !== undefined) order.name = input.name;
    if (input.description !== undefined) order.description = input.description;
    if (input.lastModifiedInSessionId !== undefined) order.lastModifiedInSessionId = input.lastModifiedInSessionId;
    if (input.trigger !== undefined) {
      order.trigger = input.trigger;
      order.triggerType = input.trigger.type;
    }
    if (input.targets !== undefined) order.targets = input.targets;
    if (input.agentPrompt !== undefined) order.agentPrompt = input.agentPrompt;
    if (input.agentSkills !== undefined) order.agentSkills = input.agentSkills;
    if (input.runbookId !== undefined) order.runbookId = input.runbookId;
    if (input.maxRiskLevel !== undefined) order.maxRiskLevel = input.maxRiskLevel;
    if (input.maxTurns !== undefined) order.maxTurns = input.maxTurns;
    if (input.maxBudgetUsd !== undefined) order.maxBudgetUsd = input.maxBudgetUsd;
    if (input.decisionBoundary !== undefined) order.decisionBoundary = input.decisionBoundary;
    if (input.escalationPolicyId !== undefined) order.escalationPolicyId = input.escalationPolicyId;
    if (input.status !== undefined) order.status = input.status;
    if (input.validUntil !== undefined) order.validUntil = input.validUntil;

    order.updatedAt = new Date();

    const saved = await this.standingOrderRepository.save(order);
    this.logger.log(`Standing order updated: ${saved.id}`);
    return saved;
  }
}
