import { z } from "zod";
import {
  adminProcedure,
  createTRPCRouter,
  protectedProcedure,
  publicProcedure,
} from "~/server/api/trpc";
import {
  EdiAnnuncioSchema,
  editAnnuncioHandler,
  getProprietarioDataHandler,
  getCodici_AnnunciHandler,
  getAnnunciListHandler,
  getOptions_AnnunciHandler,
  getAnnunciByCod,
  getCursor_AnnunciHandler,
  get_AnnunciPositionsHandler,
  getAnnunciById,
} from "~/server/controllers/annunci.controller";
import { zAnnuncioId, zServizioId } from "~/server/utils/zod_types";

export const annunciRouter = createTRPCRouter({
  getAnnunciList: publicProcedure.query(async () => {
    return await getAnnunciListHandler();
  }),
  getCodici: publicProcedure.query(async () => {
    return await getCodici_AnnunciHandler();
  }),
  getAnnuncio: publicProcedure
    .input(
      z.object({
        cod: z.string(),
      }),
    )
    .query(async ({ input }) => {
      return await getAnnunciByCod({ ...input });
    }),
  getAnnuncioById: publicProcedure
    .input(
      z.object({
        id: zAnnuncioId,
      }),
    )
    .query(async ({ input }) => {
      return await getAnnunciById({ ...input });
    }),
  getWithCursor: publicProcedure
    .input(
      z.object({
        limit: z.number().min(1).max(100).optional(),
        cursor: z.string().optional(),
        tipologia: z.string().optional(),
        comune: z.string().optional(),
        consegna: z.number().optional(),
        sort: z.enum(["Recenti", "Prezzo", "Consegna", "Mq"]).optional(),
      }),
    )
    .query(async ({ input }) => {
      const { annunci, nextCursor } = await getCursor_AnnunciHandler({
        input,
      });
      return {
        annunci,
        nextCursor,
      };
    }),
  getMapping: publicProcedure
    .input(
      z.object({
        tipologia: z.string().optional(),
        comune: z.string().optional(),
        consegna: z.number().optional(),
      }),
    )
    .query(async ({ input }) => {
      return await get_AnnunciPositionsHandler({
        ...input,
      });
    }),
  getAnnunciOptions: publicProcedure.query(async () => {
    return await getOptions_AnnunciHandler();
  }),

  editAnnuncio: adminProcedure
    .input(EdiAnnuncioSchema)
    .mutation(async ({ input }) => {
      return await editAnnuncioHandler({
        ...input,
      });
    }),

  getProprietarioData: protectedProcedure
    .input(z.object({ annuncioId: zAnnuncioId, servizioId: zServizioId }))
    .query(async ({ input }) => {
      return await getProprietarioDataHandler({
        annuncioId: input.annuncioId,
        servizioId: input.servizioId,
      });
    }),
});
