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

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

  async findAll() {
    return this.prisma.news.findMany({
      where: { status: 'PUBLISHED' },
      orderBy: { publishedAt: 'desc' },
    });
  }

  async findBySlug(slug: string) {
    const news = await this.prisma.news.findUnique({ where: { slug } });
    if (!news) throw new NotFoundException('News not found');
    return news;
  }

  async findLatest(limit: number = 5) {
    return this.prisma.news.findMany({
      where: { status: 'PUBLISHED' },
      orderBy: { publishedAt: 'desc' },
      take: limit,
    });
  }

  async adminFindAll() {
    return this.prisma.news.findMany({ orderBy: { createdAt: 'desc' } });
  }

  async create(data: { title: string; content: string; excerpt?: string; featuredImage?: string; status?: any; publishedAt?: string }) {
    const slug = slugify.default(data.title, { lower: true, strict: true });
    const createData: any = { ...data, slug };
    if (data.publishedAt) {
      createData.publishedAt = new Date(data.publishedAt);
    }
    return this.prisma.news.create({ data: createData });
  }

  async update(id: number, data: { title?: string; content?: string; excerpt?: string; featuredImage?: string; status?: any; publishedAt?: string }) {
    const updateData: any = { ...data };
    if (data.title) {
      updateData.slug = slugify.default(data.title, { lower: true, strict: true });
    }
    if (data.publishedAt) {
      updateData.publishedAt = new Date(data.publishedAt);
    }
    return this.prisma.news.update({ where: { id }, data: updateData });
  }

  async remove(id: number) {
    return this.prisma.news.delete({ where: { id } });
  }
}
