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

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

  async findAll(params: { page?: number; pageSize?: number; categoryId?: number; contentType?: string }) {
    const page = Number(params.page ?? 1);
    const pageSize = Number(params.pageSize ?? 20);
    const { categoryId, contentType } = params;
    const where: any = { status: 'PUBLISHED', deletedAt: null };
    if (categoryId) where.categoryId = categoryId;
    if (contentType) where.contentType = contentType;

    const [items, total] = await Promise.all([
      this.prisma.content.findMany({
        where,
        skip: (page - 1) * pageSize,
        take: pageSize,
        orderBy: { publishedAt: 'desc' },
        select: {
          id: true, title: true, summary: true, cover: true, contentType: true,
          tags: true, authorName: true, viewCount: true, isAiGenerated: true,
          publishedAt: true, createdAt: true, category: true,
        },
      }),
      this.prisma.content.count({ where }),
    ]);

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

  async findById(id: number) {
    const content = await this.prisma.content.findUnique({ where: { id }, include: { category: true } });
    if (!content) return null;
    await this.prisma.content.update({ where: { id }, data: { viewCount: { increment: 1 } } });
    return content;
  }

  async create(data: any) {
    return this.prisma.content.create({ data });
  }

  async update(id: number, data: any) {
    return this.prisma.content.update({ where: { id }, data });
  }

  async remove(id: number) {
    return this.prisma.content.update({ where: { id }, data: { deletedAt: new Date() } });
  }
}
