import { prisma } from '../config/database';

export const announcementRepository = {
  async list(filters?: { publishedOnly?: boolean }) {
    return prisma.announcement.findMany({
      where: filters?.publishedOnly ? { published: true } : {},
      orderBy: [{ pinned: 'desc' }, { date: 'desc' }],
    });
  },

  async findById(id: number) {
    return prisma.announcement.findUnique({ where: { id } });
  },

  async create(data: {
    title: string;
    body: string;
    author?: string | null;
    pinned?: boolean;
    published?: boolean;
  }) {
    return prisma.announcement.create({
      data: {
        title: data.title,
        body: data.body,
        author: data.author ?? null,
        pinned: data.pinned ?? false,
        published: data.published ?? true,
      },
    });
  },

  async update(
    id: number,
    data: Partial<{
      title: string;
      body: string;
      author: string | null;
      pinned: boolean;
      published: boolean;
    }>
  ) {
    return prisma.announcement.update({ where: { id }, data });
  },

  async delete(id: number) {
    return prisma.announcement.delete({ where: { id } });
  },

  async count() {
    return prisma.announcement.count();
  },
};
