import { Router } from 'express';
import { DataSource } from 'typeorm';
import { AIService } from './services';
import { AIController } from './controllers';
import {
  AIModel,
  AIPrompt,
  AIConversation,
  AIMessage,
  AIUsageLog,
  AITenantQuota,
} from './entities';

export interface AIModuleOptions {
  dataSource: DataSource;
  basePath?: string;
}

export class AIModule {
  public router: Router;
  public aiService: AIService;
  private dataSource: DataSource;
  private basePath: string;

  constructor(options: AIModuleOptions) {
    this.dataSource = options.dataSource;
    this.basePath = options.basePath || '';
    this.router = Router();
    this.initializeServices();
    this.initializeRoutes();
  }

  private initializeServices(): void {
    const modelRepository = this.dataSource.getRepository(AIModel);
    const conversationRepository = this.dataSource.getRepository(AIConversation);
    const messageRepository = this.dataSource.getRepository(AIMessage);
    const promptRepository = this.dataSource.getRepository(AIPrompt);
    const usageLogRepository = this.dataSource.getRepository(AIUsageLog);
    const quotaRepository = this.dataSource.getRepository(AITenantQuota);

    this.aiService = new AIService(
      modelRepository,
      conversationRepository,
      messageRepository,
      promptRepository,
      usageLogRepository,
      quotaRepository
    );
  }

  private initializeRoutes(): void {
    const aiController = new AIController(this.aiService);
    this.router.use(`${this.basePath}/ai`, aiController.router);
  }

  static getEntities(): Function[] {
    return [
      AIModel,
      AIPrompt,
      AIConversation,
      AIMessage,
      AIUsageLog,
      AITenantQuota,
    ];
  }
}
