/**
 * Notification query helpers.
 *
 * Creates, lists, and resolves dashboard notifications for vendors and users.
 * Used by the image moderation pipeline to surface rejection banners with
 * replace-CTA to owners.
 */

import { and, eq, isNull, sql } from 'drizzle-orm';
import { notifications } from '@/server/db/schema.js';
import type { DrizzleClient } from '@/server/db/client.js';

export interface CreateNotificationInput {
  recipientType: 'user' | 'vendor';
  recipientId: string;
  eventType: string;
  severity?: 'info' | 'warning' | 'error';
  payload: Record<string, unknown>;
}

export async function createNotification(
  db: DrizzleClient,
  input: CreateNotificationInput,
): Promise<void> {
  await db.insert(notifications).values({
    recipientType: input.recipientType,
    recipientId: input.recipientId,
    eventType: input.eventType,
    severity: input.severity ?? 'warning',
    payload: input.payload,
  });
}

export async function listUnresolvedForRecipient(
  db: DrizzleClient,
  recipientType: 'user' | 'vendor',
  recipientId: string,
) {
  return db
    .select()
    .from(notifications)
    .where(
      and(
        eq(notifications.recipientType, recipientType),
        eq(notifications.recipientId, recipientId),
        isNull(notifications.resolvedAt),
      ),
    )
    .orderBy(sql`${notifications.createdAt} DESC`)
    .limit(200);
}

/**
 * Stamp resolved_at on every unresolved image.rejected notification
 * matching (entityType, entityId, purpose). Called when a new upload
 * replaces the rejected one (pending re-review clears old rejection).
 */
export async function resolveImageNotifications(
  db: DrizzleClient,
  args: { entityType: string; entityId: string; purpose: string },
): Promise<void> {
  await db
    .update(notifications)
    .set({ resolvedAt: new Date() })
    .where(
      and(
        eq(notifications.eventType, 'image.rejected'),
        isNull(notifications.resolvedAt),
        sql`${notifications.payload}->>'entityType' = ${args.entityType}`,
        sql`${notifications.payload}->>'entityId' = ${args.entityId}`,
        sql`${notifications.payload}->>'purpose' = ${args.purpose}`,
      ),
    );
}
