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

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

  async findAll(params: { page?: number; pageSize?: number; categoryId?: number; isFeatured?: boolean; tag?: string }) {
    const page = Number(params.page ?? 1);
    const pageSize = Number(params.pageSize ?? 20);
    const { categoryId, isFeatured, tag } = params;
    const where: any = { status: 'PUBLISHED', deletedAt: null };
    if (categoryId) where.categoryId = categoryId;
    if (isFeatured !== undefined) where.isFeatured = isFeatured;
    if (tag) where.tags = { contains: tag };

    const [items, total] = await Promise.all([
      this.prisma.tool.findMany({
        where,
        skip: (page - 1) * pageSize,
        take: pageSize,
        orderBy: { viewCount: 'desc' },
        include: { category: true },
      }),
      this.prisma.tool.count({ where }),
    ]);

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

  async findBySlug(slug: string) {
    const tool = await this.prisma.tool.findUnique({
      where: { slug },
      include: { category: true },
    });
    if (!tool || tool.deletedAt) {
      throw new NotFoundException('工具不存在');
    }
    // 增加浏览量
    await this.prisma.tool.update({
      where: { id: tool.id },
      data: { viewCount: { increment: 1 } },
    });
    return tool;
  }

  async create(data: {
    name: string;
    slug: string;
    description?: string;
    url: string;
    icon?: string;
    affiliateLink?: string;
    categoryId?: number;
    tags?: string;
    metaTitle?: string;
    metaDesc?: string;
    content?: string;
  }) {
    return this.prisma.tool.create({ data });
  }
}
