import { Injectable, type OnModuleInit } from '@nestjs/common';
import { Client as TypesenseClient } from 'typesense';
import { LoggerService } from './logger.service';

/**
 * Provides a shared Typesense client for search, indexers, and health probes.
 * Lives in SharedModule so any feature module can inject it without importing
 * SearchModule.
 */
@Injectable()
export class TypesenseClientService implements OnModuleInit {
  private client!: TypesenseClient;

  constructor(private readonly logger: LoggerService) {}

  onModuleInit(): void {
    this.client = new TypesenseClient({
      nodes: [
        {
          host: process.env['TYPESENSE_HOST'] || 'localhost',
          port: parseInt(process.env['TYPESENSE_PORT'] || '8108', 10),
          protocol: process.env['TYPESENSE_PROTOCOL'] || 'http',
        },
      ],
      apiKey: process.env['TYPESENSE_API_KEY'] || 'ts_dev_key_change_me',
      connectionTimeoutSeconds: 5,
      retryIntervalSeconds: 0.1,
      numRetries: 3,
    });

    this.logger.log('TypesenseClientService initialized', 'TypesenseClient');
  }

  getClient(): TypesenseClient {
    return this.client;
  }
}
