import { Prisma } from "@/generated/prisma/client"
import { paginate } from "@/lib/paginate"
import prisma from "@/lib/prisma"
import { Category, CategorySummary, CategoryWithItemsCount } from "@/lib/types"

export const CategoryService = {
  findAll: async (): Promise<CategorySummary[]> => {
    return prisma.category.findMany({
      select: {
        id: true,
        name: true,
      },
    })
  },

  findAllWithItemsCount: async (): Promise<CategoryWithItemsCount[]> => {
    return prisma.category.findMany({
      select: {
        id: true,
        name: true,
        _count: { select: { items: true } },
      },
      orderBy: { name: "asc" },
    })
  },

  findAllWithItemsCountPaginated: async ({
    page,
    pageSize,
    search,
  }: {
    page?: number
    pageSize?: number
    search?: string
  }) => {
    return paginate<CategoryWithItemsCount>({
      model: prisma.category,
      page,
      pageSize,
      where: {
        ...(search
          ? {
              name: { contains: search, mode: "insensitive" },
            }
          : {}),
      },
      orderBy: { name: "asc" },
      select: {
        id: true,
        name: true,
        _count: { select: { items: true } },
      },
    })
  },

  findByName: async (name: string): Promise<Category | null> => {
    return prisma.category.findFirst({
      where: { name: { equals: name, mode: "insensitive" } },
    })
  },

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

  create: async (data: Prisma.CategoryCreateInput): Promise<Category> => {
    return prisma.category.create({ data })
  },

  update: async (
    id: string,
    data: Prisma.CategoryUpdateInput,
  ): Promise<Category> => {
    return prisma.category.update({ where: { id }, data })
  },

  delete: async (id: string): Promise<Category> => {
    return prisma.category.delete({ where: { id } })
  },
}
