/**
 * Service for managing per-tenant hook scripts (CRUD).
 */
import { Injectable } from '@nestjs/common';
import { HookScriptRepository } from '../repositories/hook-script.repository';
import { HookScript } from '../../domain/entities/hook-script.entity';

export interface CreateHookDto {
  name: string;
  event: string;
  toolPattern?: string;
  script: string;
  timeout?: number;
  enabled?: boolean;
  description?: string;
}

export interface UpdateHookDto {
  name?: string;
  event?: string;
  toolPattern?: string;
  script?: string;
  timeout?: number;
  enabled?: boolean;
  description?: string;
}

@Injectable()
export class HookScriptService {
  constructor(private readonly repo: HookScriptRepository) {}

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

  async create(tenantId: string, dto: CreateHookDto): Promise<HookScript> {
    const hook = new HookScript();
    hook.tenantId = tenantId;
    hook.name = dto.name;
    hook.event = dto.event;
    hook.toolPattern = dto.toolPattern ?? '*';
    hook.script = dto.script;
    hook.timeout = dto.timeout ?? 30;
    hook.enabled = dto.enabled ?? true;
    hook.description = dto.description ?? '';
    return this.repo.save(hook);
  }

  async update(id: string, tenantId: string, dto: UpdateHookDto): Promise<HookScript | null> {
    const hook = await this.repo.findOneByIdAndTenant(id, tenantId);
    if (!hook) return null;
    if (dto.name !== undefined) hook.name = dto.name;
    if (dto.event !== undefined) hook.event = dto.event;
    if (dto.toolPattern !== undefined) hook.toolPattern = dto.toolPattern;
    if (dto.script !== undefined) hook.script = dto.script;
    if (dto.timeout !== undefined) hook.timeout = dto.timeout;
    if (dto.enabled !== undefined) hook.enabled = dto.enabled;
    if (dto.description !== undefined) hook.description = dto.description;
    return this.repo.save(hook);
  }

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