import { z } from "zod";

import { TRPCError } from "@trpc/server";
import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc";
import type { Prisma } from "@prisma/client";

export const categoryRouter = createTRPCRouter({
  getCategories: protectedProcedure.query(async ({ ctx }) => {
    const categories = await ctx.prisma.category.findMany();
    return {
      categories,
    };
  }),
  addCategory: protectedProcedure
    .input(
      z.object({
        name: z.string(),
        description: z.string().nullish(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      const category: Prisma.CategoryCreateInput = {
        ...input,
        user: { connect: { id: ctx.session.user.id } },
      };
      const createdCategory = await ctx.prisma.category.create({
        data: category,
      });
      return createdCategory;
    }),
  updateCategory: protectedProcedure
    .input(
      z.object({
        id: z.number(),
        name: z.string(),
        description: z.string().nullish(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      const { id, ...categoryWithoutId } = input;
      const category: Prisma.CategoryUpdateInput = {
        ...categoryWithoutId,
        user: { connect: { id: ctx.session.user.id } },
      };

      const updatedCategory = await ctx.prisma.category.update({
        data: category,
        where: {
          id,
        },
      });
      return updatedCategory;
    }),
  deleteCategory: protectedProcedure
    .input(
      z.object({
        category_id: z.number(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      const anyProduct = await ctx.prisma.product.findFirst({
        where: {
          category_id: input.category_id,
        },
      });
      if (anyProduct === null) {
        const deleteCategory = await ctx.prisma.category.delete({
          where: {
            id: input.category_id,
          },
        });
      } else {
        throw new TRPCError({
          code: "BAD_REQUEST",
          message:
            "Esta categoria tem produtos associados, não é possível excluí-la.",
        });
      }
    }),
});
