import { ok, err, type ReadonlyDB, type QueryContext } from "@tailor-platform/erp-kit/core";
import type { DB } from "../generated/kysely-tailordb";
import { ForbiddenError } from "../lib/errors.generated";

export interface GetNotificationPreferenceInput {
  userId: string;
  categoryId: string;
  channelId: string;
}

/**
 * Returns the caller's NotificationPreference row for a (categoryId, channelId), or null (default opt-in). Self-service only.
 */
export async function run(
  db: ReadonlyDB<DB>,
  input: GetNotificationPreferenceInput,
  ctx: QueryContext,
) {
  const { userId, categoryId, channelId } = input;

  if (ctx.actorId !== userId) {
    return err(new ForbiddenError(userId));
  }

  const preference = await db
    .selectFrom("NotificationPreference")
    .selectAll()
    .where("userId", "=", userId)
    .where("categoryId", "=", categoryId)
    .where("channelId", "=", channelId)
    .executeTakeFirst();

  return ok({ preference: preference ?? null });
}
