import { Injectable, NotFoundException } from "@nestjs/common"; import { Prisma } from "@prisma/client"; import { PrismaService } from "../prisma/prisma.service"; import { PaginationDto } from "../common/dto/pagination.dto"; export interface BlogFilterDto extends PaginationDto { categorySlug?: string; tagSlug?: string; featured?: boolean | string; } @Injectable() export class BlogsService { constructor(private prisma: PrismaService) {} async findAll(filters: BlogFilterDto) { const { search, page = 1, limit = 10, sortBy = "publishedAt", sortOrder = "desc", categorySlug, tagSlug, featured, } = filters; const now = new Date(); const whereClause: Prisma.BlogWhereInput = { isPublished: true, status: "PUBLISHED", OR: [{ publishedAt: null }, { publishedAt: { lte: now } }], }; if (search) { whereClause.AND = [ { OR: [ { title: { contains: search, mode: "insensitive" } }, { excerpt: { contains: search, mode: "insensitive" } }, { content: { contains: search, mode: "insensitive" } }, { keywords: { contains: search, mode: "insensitive" } }, ], }, ]; } if (categorySlug) { whereClause.category = { slug: categorySlug }; } if (tagSlug) { whereClause.tags = { some: { slug: tagSlug } }; } if (featured !== undefined && featured !== "") { whereClause.featured = String(featured) === "true"; } const skip = (Number(page) - 1) * Number(limit); const [data, total] = await Promise.all([ this.prisma.blog.findMany({ where: whereClause, skip, take: Number(limit), orderBy: [ { [sortBy === "createdAt" ? "createdAt" : "publishedAt"]: sortOrder, }, { id: "asc" }, ], include: { author: { select: { id: true, firstName: true, lastName: true }, }, category: { select: { id: true, name: true, slug: true }, }, tags: { select: { id: true, name: true, slug: true }, }, _count: { select: { comments: { where: { status: "APPROVED" } } }, }, }, }), this.prisma.blog.count({ where: whereClause }), ]); return { data, meta: { total, page: Number(page), lastPage: Math.ceil(total / Number(limit)) || 1, limit: Number(limit), }, }; } async findHomepage() { const now = new Date(); const baseWhere: Prisma.BlogWhereInput = { isPublished: true, status: "PUBLISHED", OR: [{ publishedAt: null }, { publishedAt: { lte: now } }], }; // Find blogs that have showOnHome = true (selected mode) const selectedBlogs = await this.prisma.blog.findMany({ where: { ...baseWhere, showOnHome: true }, take: 4, orderBy: [{ publishedAt: "desc" }, { id: "asc" }], include: { author: { select: { id: true, firstName: true, lastName: true }, }, category: { select: { id: true, name: true, slug: true } }, tags: { select: { id: true, name: true, slug: true } }, _count: { select: { comments: { where: { status: "APPROVED" } } } }, }, }); if (selectedBlogs.length > 0) { return { mode: "selected", blogs: selectedBlogs }; } // Fallback: return newest published blogs const newestBlogs = await this.prisma.blog.findMany({ where: baseWhere, take: 4, orderBy: [{ publishedAt: "desc" }, { id: "asc" }], include: { author: { select: { id: true, firstName: true, lastName: true }, }, category: { select: { id: true, name: true, slug: true } }, tags: { select: { id: true, name: true, slug: true } }, _count: { select: { comments: { where: { status: "APPROVED" } } } }, }, }); return { mode: "newest", blogs: newestBlogs }; } async findOneBySlug(rawSlug: string) { if (!rawSlug) { throw new NotFoundException("مقاله یافت نشد"); } let decodedSlug = rawSlug; try { decodedSlug = decodeURIComponent(rawSlug); } catch { decodedSlug = rawSlug; } const isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test( decodedSlug, ); const blog = await this.prisma.blog.findFirst({ where: { OR: [ { slug: decodedSlug }, { slug: rawSlug }, ...(isUuid ? [{ id: decodedSlug }] : []), ], }, include: { author: { select: { id: true, firstName: true, lastName: true } }, category: { select: { id: true, name: true, slug: true }, }, tags: { select: { id: true, name: true, slug: true }, }, _count: { select: { comments: { where: { status: "APPROVED" } } }, }, }, }); if (!blog) { throw new NotFoundException("مقاله یافت نشد"); } // Public route must not expose scheduled, draft, or future published posts const now = new Date(); const isReady = blog.isPublished && blog.status === "PUBLISHED" && (!blog.publishedAt || blog.publishedAt <= now); if (!isReady) { throw new NotFoundException("مقاله یافت نشد"); } // Fetch related products safely let relatedProducts: any[] = []; if ( blog.relatedProductIds && Array.isArray(blog.relatedProductIds) && blog.relatedProductIds.length > 0 ) { const validProductUuids = blog.relatedProductIds.filter( (id) => typeof id === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test( id, ), ); if (validProductUuids.length > 0) { try { relatedProducts = await this.prisma.product.findMany({ where: { id: { in: validProductUuids } }, select: { id: true, nameFa: true, slug: true, priceValue: true, priceDisplay: true, imageUrl: true, categorySlug: true, unit: true, }, }); } catch (err) { console.warn("[BlogsService] Error fetching related products:", err); } } } // Fetch related blogs safely let relatedBlogs: any[] = []; if ( blog.relatedBlogIds && Array.isArray(blog.relatedBlogIds) && blog.relatedBlogIds.length > 0 ) { const validBlogUuids = blog.relatedBlogIds.filter( (id) => typeof id === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test( id, ), ); if (validBlogUuids.length > 0) { try { relatedBlogs = await this.prisma.blog.findMany({ where: { id: { in: validBlogUuids }, isPublished: true, status: "PUBLISHED", }, select: { id: true, title: true, slug: true, imageUrl: true, readingTime: true, publishedAt: true, createdAt: true, category: { select: { name: true, slug: true } }, }, }); } catch (err) { console.warn("[BlogsService] Error fetching related blogs:", err); } } } else if (blog.categoryId) { try { relatedBlogs = await this.prisma.blog.findMany({ where: { categoryId: blog.categoryId, id: { not: blog.id }, isPublished: true, status: "PUBLISHED", }, take: 3, select: { id: true, title: true, slug: true, imageUrl: true, readingTime: true, publishedAt: true, createdAt: true, category: { select: { name: true, slug: true } }, }, }); } catch (err) { console.warn( "[BlogsService] Error fetching fallback related blogs:", err, ); } } // Increment view count asynchronously this.prisma.blog .update({ where: { id: blog.id }, data: { viewCount: { increment: 1 } }, }) .catch(() => null); return { ...blog, viewCount: (blog.viewCount || 0) + 1, relatedProducts, relatedBlogs, }; } async getCategories() { return this.prisma.blogCategory.findMany({ orderBy: { order: "asc" }, include: { children: true, _count: { select: { blogs: { where: { isPublished: true, status: "PUBLISHED" } }, }, }, }, }); } async getTags() { return this.prisma.blogTag.findMany({ orderBy: { createdAt: "desc" }, include: { _count: { select: { blogs: { where: { isPublished: true, status: "PUBLISHED" } }, }, }, }, }); } async incrementView(slug: string) { const blog = await this.prisma.blog.findUnique({ where: { slug }, select: { id: true, viewCount: true }, }); if (!blog) throw new NotFoundException("مقاله یافت نشد"); const updated = await this.prisma.blog.update({ where: { id: blog.id }, data: { viewCount: { increment: 1 } }, select: { id: true, viewCount: true }, }); return { success: true, viewCount: updated.viewCount }; } async findCommentsBySlug(slug: string) { const blog = await this.prisma.blog.findUnique({ where: { slug }, select: { id: true, allowComments: true }, }); if (!blog) throw new NotFoundException("مقاله یافت نشد"); return this.prisma.blogComment.findMany({ where: { blogId: blog.id, status: "APPROVED" }, orderBy: { createdAt: "desc" }, }); } async addComment( slug: string, data: { userName: string; email?: string; content: string; userId?: string; }, ) { const blog = await this.prisma.blog.findUnique({ where: { slug }, select: { id: true, allowComments: true }, }); if (!blog) throw new NotFoundException("مقاله یافت نشد"); if (!blog.allowComments) { throw new NotFoundException("ارسال دیدگاه برای این مقاله غیرفعال است"); } return this.prisma.blogComment.create({ data: { blogId: blog.id, userName: data.userName, content: data.content, userId: data.userId, status: "PENDING", }, }); } }