import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { AiConfig } from './ai-config.entity';
import { CreateAiConfigDto } from './dto/create-ai-config.dto';
import { Workspace } from '../workspace/workspace.entity';
import { NotFoundException } from '@nestjs/common';

@Injectable()
export class AiConfigService {
  constructor(
    @InjectRepository(AiConfig)
    private aiConfigRepository: Repository<AiConfig>,
    @InjectRepository(Workspace)
    private workspaceRepository: Repository<Workspace>,
  ) {}

  async getAiConfig() {
    return await this.aiConfigRepository.find();
  }

  async createAiConfig(createAiConfigDto: CreateAiConfigDto, workspaceId: number = 1) {
    const workspace = await this.workspaceRepository.findOneBy({ id: workspaceId });
    if (!workspace) {
      throw new NotFoundException('工作区不存在');
    }
    
    const aiConfig = this.aiConfigRepository.create({
      ...createAiConfigDto,
      workspace,
    });
    
    return await this.aiConfigRepository.save(aiConfig);
  }

  // 新增根据工作区获取AI配置的方法
  async getAiConfigByWorkspace(workspaceId: number) {
    return await this.aiConfigRepository.findOne({ 
      where: { workspace: { id: workspaceId } },
      select: ['id', 'apiUrl', 'apiKey']
    });
  }
}