/**
 * Service for managing per-tenant agent configuration (engine, system prompt, max turns, budget, tools).
 */
import { Injectable } from '@nestjs/common';
import { AgentConfigRepository } from '../repositories/agent-config.repository';
import { AgentConfig } from '../../domain/entities/agent-config.entity';

export interface UpdateAgentConfigDto {
  engine?: string;
  system_prompt?: string;
  max_turns?: number;
  max_budget?: number;
  allowed_tools?: string[];
}

@Injectable()
export class AgentConfigService {
  constructor(private readonly repo: AgentConfigRepository) {}

  async findByTenantId(tenantId: string): Promise<AgentConfig | null> {
    return this.repo.findByTenantId(tenantId);
  }

  async create(tenantId: string, dto: UpdateAgentConfigDto): Promise<AgentConfig> {
    const config = new AgentConfig();
    config.tenantId = tenantId;
    this.applyDto(config, dto);
    return this.repo.save(config);
  }

  async update(id: string, tenantId: string, dto: UpdateAgentConfigDto): Promise<AgentConfig | null> {
    const config = await this.repo.findByTenantId(tenantId);
    if (!config || config.id !== id) return null;
    this.applyDto(config, dto);
    return this.repo.save(config);
  }

  private applyDto(config: AgentConfig, dto: UpdateAgentConfigDto): void {
    if (dto.engine !== undefined) config.engine = dto.engine;
    if (dto.system_prompt !== undefined) config.systemPrompt = dto.system_prompt;
    if (dto.max_turns !== undefined) config.maxTurns = dto.max_turns;
    if (dto.max_budget !== undefined) config.maxBudget = dto.max_budget;
    if (dto.allowed_tools !== undefined) config.allowedTools = dto.allowed_tools;
  }
}
