import type { SanitizedConfig } from "payload";
import type { AuditLogProtocol } from "@repo/core-shared/di";
import type { IConsent } from "../consent.interface";
import { PayloadConsent } from "../payload-consent";

export type ConsentFactory = (userId: string) => Promise<IConsent>;

export type BindProductionConsentOpts = {
  config: SanitizedConfig;
  auditLog?: AuditLogProtocol;
};

const noopAuditLog: AuditLogProtocol = { record: async () => {} };

/**
 * Returns a ConsentFactory that creates Payload-backed PayloadConsent
 * instances pre-loaded with the user's stored consent state.
 *
 * Wired by the app aggregator alongside feature binders. Call the returned
 * factory at request time with the authenticated userId to obtain an IConsent
 * bound to that user's record in the Payload `users` collection.
 */
export function bindProductionConsent(opts: BindProductionConsentOpts): {
  consentFactory: ConsentFactory;
} {
  const auditLog = opts.auditLog ?? noopAuditLog;
  const factory: ConsentFactory = async (userId) => {
    const consent = new PayloadConsent(userId, opts.config, auditLog);
    await consent.load();
    return consent;
  };
  return { consentFactory: factory };
}
