/**
 * Service for managing per-tenant agent skills (CRUD).
 */
import { Injectable } from '@nestjs/common';
import { AgentSkillRepository } from '../repositories/agent-skill.repository';
import { AgentSkill } from '../../domain/entities/agent-skill.entity';

export interface CreateSkillDto {
  name: string;
  description?: string;
  category?: string;
  script?: string;
  tags?: string[];
  enabled?: boolean;
}

export interface UpdateSkillDto {
  name?: string;
  description?: string;
  category?: string;
  script?: string;
  tags?: string[];
  enabled?: boolean;
}

@Injectable()
export class AgentSkillService {
  constructor(private readonly repo: AgentSkillRepository) {}

  async findAllByTenant(tenantId: string): Promise<{ data: AgentSkill[]; total: number }> {
    const skills = await this.repo.findByTenantId(tenantId);
    return { data: skills, total: skills.length };
  }

  async create(tenantId: string, dto: CreateSkillDto): Promise<AgentSkill> {
    const skill = new AgentSkill();
    skill.tenantId = tenantId;
    skill.name = dto.name;
    skill.description = dto.description ?? '';
    skill.category = dto.category ?? 'custom';
    skill.script = dto.script ?? '';
    skill.tags = dto.tags ?? [];
    skill.enabled = dto.enabled ?? true;
    return this.repo.save(skill);
  }

  async update(id: string, tenantId: string, dto: UpdateSkillDto): Promise<AgentSkill | null> {
    const skill = await this.repo.findOneByIdAndTenant(id, tenantId);
    if (!skill) return null;
    if (dto.name !== undefined) skill.name = dto.name;
    if (dto.description !== undefined) skill.description = dto.description;
    if (dto.category !== undefined) skill.category = dto.category;
    if (dto.script !== undefined) skill.script = dto.script;
    if (dto.tags !== undefined) skill.tags = dto.tags;
    if (dto.enabled !== undefined) skill.enabled = dto.enabled;
    return this.repo.save(skill);
  }

  async delete(id: string, tenantId: string): Promise<boolean> {
    const skill = await this.repo.findOneByIdAndTenant(id, tenantId);
    if (!skill) return false;
    await this.repo.deleteById(id);
    return true;
  }
}
