import { TRPCError } from "@trpc/server";
import { z } from "zod";
import {
  CreateReminderInputSchema,
  ListRemindersInputSchema,
  type NotificationProcedureContext,
  NotificationIdInputSchema,
  resolveUserId,
  UpdateReminderInputSchema,
} from "./notification-procedure-base.js";

export async function createReminder(
  ctx: NotificationProcedureContext,
  input: z.infer<typeof CreateReminderInputSchema>,
) {
  const userId = await resolveUserId(ctx);
  return ctx.db.notification.create({
    data: {
      userId,
      type: "REMINDER",
      category: "REMINDER",
      title: input.title,
      ...(input.body !== undefined ? { body: input.body } : {}),
      remindAt: input.remindAt,
      nextRemindAt: input.remindAt,
      ...(input.recurrence !== undefined ? { recurrence: input.recurrence } : {}),
      ...(input.entityId !== undefined ? { entityId: input.entityId } : {}),
      ...(input.entityType !== undefined ? { entityType: input.entityType } : {}),
      ...(input.link !== undefined ? { link: input.link } : {}),
      channel: "in_app",
    },
  });
}

export async function updateReminder(
  ctx: NotificationProcedureContext,
  input: z.infer<typeof UpdateReminderInputSchema>,
) {
  const userId = await resolveUserId(ctx);
  const existing = await ctx.db.notification.findFirst({
    where: { id: input.id, userId, category: "REMINDER" },
  });

  if (!existing) {
    throw new TRPCError({
      code: "NOT_FOUND",
      message: "Reminder not found or you do not have permission",
    });
  }

  return ctx.db.notification.update({
    where: { id: input.id },
    data: {
      ...(input.title !== undefined ? { title: input.title } : {}),
      ...(input.body !== undefined ? { body: input.body } : {}),
      ...(input.remindAt !== undefined
        ? { remindAt: input.remindAt, nextRemindAt: input.remindAt }
        : {}),
      ...(input.recurrence !== undefined ? { recurrence: input.recurrence } : {}),
    },
  });
}

export async function deleteReminder(
  ctx: NotificationProcedureContext,
  input: z.infer<typeof NotificationIdInputSchema>,
) {
  const userId = await resolveUserId(ctx);
  const existing = await ctx.db.notification.findFirst({
    where: { id: input.id, userId, category: "REMINDER" },
  });

  if (!existing) {
    throw new TRPCError({
      code: "NOT_FOUND",
      message: "Reminder not found or you do not have permission",
    });
  }

  await ctx.db.notification.delete({ where: { id: input.id } });
}

export async function listReminders(
  ctx: NotificationProcedureContext,
  input: z.infer<typeof ListRemindersInputSchema>,
) {
  const userId = await resolveUserId(ctx);
  return ctx.db.notification.findMany({
    where: { userId, category: "REMINDER" },
    orderBy: { nextRemindAt: "asc" },
    take: input.limit,
  });
}
