import { COOKIE_NAME } from "@shared/const";
import { getSessionCookieOptions } from "./_core/cookies";
import { systemRouter } from "./_core/systemRouter";
import { publicProcedure, router } from "./_core/trpc";
import { z } from "zod";
import { getDb } from "./db";
import { appointments, contacts } from "../drizzle/schema";

export const appRouter = router({
  system: systemRouter,
  auth: router({
    me: publicProcedure.query(opts => opts.ctx.user),
    logout: publicProcedure.mutation(({ ctx }) => {
      const cookieOptions = getSessionCookieOptions(ctx.req);
      ctx.res.clearCookie(COOKIE_NAME, { ...cookieOptions, maxAge: -1 });
      return {
        success: true,
      } as const;
    }),
  }),

  clinic: router({
    createAppointment: publicProcedure
      .input(
        z.object({
          name: z.string().min(1, "नाम आवश्यक है"),
          mobile: z.string().min(10, "मान्य मोबाइल नंबर आवश्यक है"),
          address: z.string().optional(),
          service: z.string(),
          problem: z.string().optional(),
          date: z.string().optional(),
          time: z.string().optional(),
          message: z.string().optional(),
        })
      )
      .mutation(async ({ input }) => {
        const db = await getDb();
        if (!db) {
          throw new Error("डेटाबेस से संपर्क नहीं हो सका");
        }
        await db.insert(appointments).values({
          name: input.name,
          mobile: input.mobile,
          address: input.address || "",
          service: input.service,
          problem: input.problem || "",
          date: input.date || "",
          time: input.time || "",
          message: input.message || "",
          status: "pending",
        });
        return { success: true, message: "अपॉइंटमेंट सफलतापूर्वक बुक हो गया है!" };
      }),

    submitContact: publicProcedure
      .input(
        z.object({
          name: z.string().min(1, "नाम आवश्यक है"),
          mobile: z.string().min(10, "मान्य मोबाइल नंबर आवश्यक है"),
          message: z.string().min(1, "संदेश आवश्यक है"),
        })
      )
      .mutation(async ({ input }) => {
        const db = await getDb();
        if (!db) {
          throw new Error("डेटाबेस से संपर्क नहीं हो सका");
        }
        await db.insert(contacts).values({
          name: input.name,
          mobile: input.mobile,
          message: input.message,
        });
        return { success: true, message: "आपका संदेश प्राप्त हो गया है!" };
      }),
  }),
});

export type AppRouter = typeof appRouter;
