import { Injectable, NotFoundException, ConflictException } from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";
import { CreateAgentTemplateDto } from "./dto/create-agent-template.dto";
import { UpdateAgentTemplateDto } from "./dto/update-agent-template.dto";

@Injectable()
export class AgentTemplateService {
  constructor(private readonly prisma: PrismaService) {}

  async findAll() {
    return this.prisma.agentTemplate.findMany({
      orderBy: { createdAt: "asc" },
    });
  }

  async findOne(id: string) {
    const template = await this.prisma.agentTemplate.findUnique({ where: { id } });
    if (!template) throw new NotFoundException(`AgentTemplate ${id} not found`);
    return template;
  }

  async findByName(name: string) {
    const template = await this.prisma.agentTemplate.findUnique({ where: { name } });
    if (!template) throw new NotFoundException(`AgentTemplate "${name}" not found`);
    return template;
  }

  async create(dto: CreateAgentTemplateDto) {
    const existing = await this.prisma.agentTemplate.findUnique({ where: { name: dto.name } });
    if (existing) throw new ConflictException(`AgentTemplate "${dto.name}" already exists`);

    return this.prisma.agentTemplate.create({
      data: {
        name: dto.name,
        displayName: dto.displayName,
        role: dto.role,
        personality: dto.personality,
        primaryModel: dto.primaryModel,
        fallbackModels: dto.fallbackModels ?? ([] as string[]),
        toolPermissions: dto.toolPermissions ?? ([] as string[]),
        ...(dto.discordChannel !== undefined && { discordChannel: dto.discordChannel }),
        isActive: dto.isActive ?? true,
        isDefault: dto.isDefault ?? false,
      },
    });
  }

  async update(id: string, dto: UpdateAgentTemplateDto) {
    await this.findOne(id);
    return this.prisma.agentTemplate.update({ where: { id }, data: dto });
  }

  async remove(id: string) {
    await this.findOne(id);
    return this.prisma.agentTemplate.delete({ where: { id } });
  }
}
