import { Prisma, Recipient } from "@/generated/prisma/client"
import { paginate } from "@/lib/paginate"
import prisma from "@/lib/prisma"

export const RecipientService = {
  findAll: async (): Promise<Recipient[]> => {
    return prisma.recipient.findMany({
      orderBy: {
        firstName: "asc",
      },
    })
  },
  findAllPaginated: async ({
    page = 0,
    pageSize,
    search,
  }: {
    page?: number
    pageSize?: number
    search?: string
  }) => {
    return paginate<Recipient>({
      model: prisma.recipient,
      page,
      pageSize,
      where: {
        ...(search
          ? {
              OR: [
                { username: { contains: search, mode: "insensitive" } },
                { firstName: { contains: search, mode: "insensitive" } },
                { lastName: { contains: search, mode: "insensitive" } },
              ],
            }
          : {}),
      },
    })
  },
  findAllRecipientsCount: async (): Promise<number> => {
    return prisma.recipient.count()
  },

  findById: async (id: string): Promise<Recipient | null> => {
    return prisma.recipient.findUnique({ where: { id } })
  },

  findByUsername: async (username: string): Promise<Recipient | null> => {
    return prisma.recipient.findUnique({ where: { username } })
  },

  findByEmail: async (email: string): Promise<Recipient | null> => {
    return prisma.recipient.findUnique({ where: { email } })
  },

  create: async (data: Prisma.RecipientCreateInput): Promise<Recipient> => {
    return prisma.recipient.create({ data })
  },
}
