import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, IsNull } from 'typeorm';
import { McpServerConfigORM } from '../entities/mcp-server-config.orm';
import { McpServerConfig } from '../../../agents/mcp/mcp.types';

@Injectable()
export class McpServerConfigRepository {
  constructor(
    @InjectRepository(McpServerConfigORM)
    private readonly repo: Repository<McpServerConfigORM>,
  ) {}

  async findAll(tenantId?: string | null): Promise<McpServerConfigORM[]> {
    return this.repo.find({
      where: { tenantId: tenantId ?? IsNull() },
      order: { createdAt: 'DESC' },
    });
  }

  async findEnabled(tenantId?: string | null): Promise<McpServerConfigORM[]> {
    return this.repo.find({
      where: { tenantId: tenantId ?? IsNull(), enabled: true },
      order: { createdAt: 'DESC' },
    });
  }

  async findById(id: string): Promise<McpServerConfigORM | null> {
    return this.repo.findOne({ where: { id } });
  }

  async findByServerId(serverId: string, tenantId?: string | null): Promise<McpServerConfigORM | null> {
    return this.repo.findOne({
      where: { serverId, tenantId: tenantId ?? IsNull() },
    });
  }

  async create(data: Partial<McpServerConfigORM>): Promise<McpServerConfigORM> {
    const entity = this.repo.create(data);
    return this.repo.save(entity);
  }

  async update(id: string, data: Partial<McpServerConfigORM>): Promise<McpServerConfigORM | null> {
    await this.repo.update(id, data);
    return this.findById(id);
  }

  async remove(id: string): Promise<void> {
    await this.repo.delete(id);
  }

  /** Convert ORM entity to McpServerConfig for McpClientService */
  toMcpServerConfig(orm: McpServerConfigORM): McpServerConfig {
    return {
      id: orm.serverId,
      name: orm.name,
      transport: orm.transport,
      command: orm.command || undefined,
      args: orm.args || undefined,
      env: orm.env || undefined,
      url: orm.url || undefined,
      toolsConcurrencySafe: orm.toolsConcurrencySafe,
      connectTimeoutMs: orm.connectTimeoutMs,
      toolTimeoutMs: orm.toolTimeoutMs,
      enabled: orm.enabled,
    };
  }
}
