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

export interface ScheduleRecurringTaskInput {
  tenantId: string;
  name: string;
  description?: string;
  cronExpression: string;
  agentPrompt: string;
  agentSkills?: string[];
  targetServerIds?: string[];
  runbookId?: string;
  maxRiskLevel?: 0 | 1;
  maxTurns?: number;
  createdBy: string;
}

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

  constructor(
    private readonly standingOrderRepository: StandingOrderRepository,
    private readonly runbookRepository: RunbookRepository,
  ) {}

  async execute(input: ScheduleRecurringTaskInput): Promise<StandingOrder> {
    this.logger.log(`Scheduling recurring task: ${input.name}`);

    if (input.runbookId) {
      const runbook = await this.runbookRepository.findById(input.runbookId);
      if (!runbook) {
        throw new Error(`Runbook ${input.runbookId} not found`);
      }
    }

    const order = new StandingOrder();
    order.id = crypto.randomUUID().slice(0, 30);
    order.tenantId = input.tenantId;
    order.name = input.name;
    order.description = input.description;
    order.definedInSessionId = crypto.randomUUID();
    order.triggerType = 'cron';
    order.trigger = {
      type: 'cron',
      cronExpression: input.cronExpression,
    };
    order.targets = {
      serverIds: input.targetServerIds,
    };
    order.agentPrompt = input.agentPrompt;
    order.agentSkills = input.agentSkills;
    order.runbookId = input.runbookId;
    order.maxRiskLevel = input.maxRiskLevel ?? 0;
    order.maxTurns = input.maxTurns ?? 20;
    order.decisionBoundary = {
      allowedActions: [],
      escalateConditions: ['on_failure'],
      escalationRules: [],
    };
    order.status = 'active';
    order.validFrom = new Date();
    order.createdBy = input.createdBy;
    order.createdAt = new Date();
    order.updatedAt = new Date();

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