import { Injectable, NotFoundException } from '@nestjs/common';
import { PrismaService } from '@chatapp/database';

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

  async list(wsId: string, query: { category?: string; type?: string } = {}) {
    const where: any = {
      OR: [
        { workspaceId: wsId, isCustom: true },
        { isCustom: false },
      ],
    };
    if (query.category) where.category = query.category;
    if (query.type) where.type = query.type;

    const templates = await this.prisma.template.findMany({
      where,
      orderBy: { name: 'asc' },
      include: {
        createdByUser: { select: { id: true, displayName: true, avatarUrl: true } },
      },
    });

    return {
      templates: templates.map(t => ({
        id: t.id,
        name: t.name,
        description: t.description,
        category: t.category,
        type: t.type,
        content: t.content,
        is_custom: t.isCustom,
        created_by: t.createdByUser,
        created_at: t.createdAt,
      })),
    };
  }

  async findById(id: string, wsId: string) {
    const template = await this.prisma.template.findFirst({
      where: {
        id,
        OR: [
          { workspaceId: wsId, isCustom: true },
          { isCustom: false },
        ],
      },
      include: {
        createdByUser: { select: { id: true, displayName: true, avatarUrl: true } },
      },
    });

    if (!template) throw new NotFoundException('Template not found');

    return {
      id: template.id,
      name: template.name,
      description: template.description,
      category: template.category,
      type: template.type,
      content: template.content,
      is_custom: template.isCustom,
      created_by: template.createdByUser,
      created_at: template.createdAt,
    };
  }

  async create(wsId: string, userId: string, dto: any) {
    const template = await this.prisma.template.create({
      data: {
        workspaceId: wsId,
        name: dto.name,
        description: dto.description,
        category: dto.category,
        content: dto.content ?? {},
        type: dto.type || 'canvas',
        isCustom: true,
        createdBy: userId,
      },
      include: {
        createdByUser: { select: { id: true, displayName: true, avatarUrl: true } },
      },
    });

    return {
      id: template.id,
      name: template.name,
      description: template.description,
      category: template.category,
      type: template.type,
      content: template.content,
      is_custom: template.isCustom,
      created_by: template.createdByUser,
      created_at: template.createdAt,
    };
  }

  async update(id: string, wsId: string, userId: string, dto: any) {
    const template = await this.prisma.template.findFirst({
      where: { id, workspaceId: wsId, isCustom: true },
    });
    if (!template) throw new NotFoundException('Template not found');

    const data: any = {};
    if (dto.name !== undefined) data.name = dto.name;
    if (dto.description !== undefined) data.description = dto.description;
    if (dto.category !== undefined) data.category = dto.category;
    if (dto.content !== undefined) data.content = dto.content;
    if (dto.type !== undefined) data.type = dto.type;

    return this.prisma.template.update({ where: { id }, data });
  }

  async delete(id: string, wsId: string) {
    const template = await this.prisma.template.findFirst({
      where: { id, workspaceId: wsId, isCustom: true },
    });
    if (!template) throw new NotFoundException('Template not found');

    await this.prisma.template.delete({ where: { id } });
    return { deleted: true };
  }
}