import { Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { NetaClawMemoryTypeEntity } from '../entity/memory_type.js';

@Provide()
export class MemoryTypeService extends BaseService {
  @InjectEntityModel(NetaClawMemoryTypeEntity)
  memoryTypeEntity: Repository<NetaClawMemoryTypeEntity>;

  async deleteWithCheck(ids: number[]): Promise<void> {
    await this.memoryTypeEntity.manager.transaction(async manager => {
      const repo = manager.getRepository(NetaClawMemoryTypeEntity);
      const systemTypes = await repo.find({
        where: ids.map(id => ({ id, isSystem: 1 })),
      });

      if (systemTypes.length > 0) {
        const names = systemTypes.map(t => t.name).join(', ');
        throw new Error(`系统内置类型不可删除: ${names}`);
      }

      await repo.delete(ids);
    });
  }

  async allTypes(): Promise<NetaClawMemoryTypeEntity[]> {
    return this.memoryTypeEntity.find({ order: { isSystem: 'DESC', createTime: 'ASC' } });
  }
}
