import { z } from "zod";
import { COOKIE_NAME } from "@shared/const";
import { getSessionCookieOptions } from "./_core/cookies";
import { systemRouter } from "./_core/systemRouter";
import { publicProcedure, router } from "./_core/trpc";
import { createLead } from "./db";
import { notifyOwner } from "./_core/notification";

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;
    }),
  }),

  leads: router({
    submit: publicProcedure
      .input(z.object({
        name: z.string().min(1, "Name is required"),
        email: z.string().email("Valid email required"),
        phone: z.string().optional(),
        company: z.string().optional(),
        serviceInterest: z.enum(["Marketing", "Staffing", "Financial Consultation"]),
        message: z.string().optional(),
      }))
      .mutation(async ({ input }) => {
        const lead = await createLead({
          name: input.name,
          email: input.email,
          phone: input.phone || null,
          company: input.company || null,
          serviceInterest: input.serviceInterest,
          message: input.message || null,
        });

        // Send notification to owner
        try {
          await notifyOwner({
            title: `New Lead: ${input.name}`,
            content: `A new lead has been submitted.\n\nName: ${input.name}\nEmail: ${input.email}\nPhone: ${input.phone || "N/A"}\nCompany: ${input.company || "N/A"}\nService Interest: ${input.serviceInterest}\nMessage: ${input.message || "N/A"}`,
          });
        } catch (error) {
          console.error("Failed to send owner notification:", error);
        }

        return lead;
      }),
  }),

  // TODO: add feature routers here, e.g.
  // todo: router({
  //   list: protectedProcedure.query(({ ctx }) =>
  //     db.getUserTodos(ctx.user.id)
  //   ),
  // }),
});

export type AppRouter = typeof appRouter;
