import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';

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

  async findAll(params: { page?: number; pageSize?: number; categoryId?: number; search?: string }) {
    const page = Number(params.page ?? 1);
    const pageSize = Number(params.pageSize ?? 20);
    const { categoryId, search } = params;
    const where: any = { status: 'PUBLISHED', deletedAt: null, isPublic: true };
    if (categoryId) where.categoryId = categoryId;
    if (search) {
      where.OR = [
        { title: { contains: search } },
        { content: { contains: search } },
      ];
    }

    const [items, total] = await Promise.all([
      this.prisma.prompt.findMany({
        where,
        skip: (page - 1) * pageSize,
        take: pageSize,
        orderBy: { likeCount: 'desc' },
        select: {
          id: true, title: true, description: true, content: true,
          tags: true, model: true, viewCount: true, likeCount: true,
          createdAt: true, category: true, author: { select: { nickname: true } },
        },
      }),
      this.prisma.prompt.count({ where }),
    ]);

    return { items, total, page, pageSize };
  }

  async findById(id: number) {
    await this.prisma.prompt.update({ where: { id }, data: { viewCount: { increment: 1 } } });
    return this.prisma.prompt.findUnique({
      where: { id },
      include: { category: true, author: { select: { nickname: true } } },
    });
  }

  async create(data: { title: string; content: string; description?: string; categoryId?: number; tags?: string; model?: string; authorId?: number }) {
    return this.prisma.prompt.create({ data });
  }

  async toggleFavorite(userId: number, promptId: number) {
    const existing = await this.prisma.promptFavorite.findUnique({
      where: { userId_promptId: { userId, promptId } },
    });

    if (existing) {
      await this.prisma.promptFavorite.delete({ where: { id: existing.id } });
      await this.prisma.prompt.update({ where: { id: promptId }, data: { likeCount: { decrement: 1 } } });
      return { favorited: false };
    }

    await this.prisma.promptFavorite.create({ data: { userId, promptId } });
    await this.prisma.prompt.update({ where: { id: promptId }, data: { likeCount: { increment: 1 } } });
    return { favorited: true };
  }

  async findFavorites(userId: number, params: { page?: number; pageSize?: number }) {
    const page = Number(params.page ?? 1);
    const pageSize = Number(params.pageSize ?? 20);
    const [items, total] = await Promise.all([
      this.prisma.promptFavorite.findMany({
        where: { userId },
        skip: (page - 1) * pageSize,
        take: pageSize,
        orderBy: { createdAt: 'desc' },
        include: { prompt: true },
      }),
      this.prisma.promptFavorite.count({ where: { userId } }),
    ]);
    return { items, total, page, pageSize };
  }
}
