/**
 * countedConversionWhere — canonical Prisma WHERE clause for user-facing
 * conversion counts.
 *
 * Applies four gates by default:
 *   1. isDuplicateOf: null          — exclude dedup-marked duplicates
 *   2. invalidatedReason: null      — exclude forensic-only invalid rows
 *   3. conversionType notIn EXCLUDED — exclude structural signal types
 *   4. successConfirmed: true       — only when opts.requireSuccessConfirmed=true
 *
 * Every analytics query that shows a conversion number to a user MUST use this
 * helper. Queries that intentionally read raw or unfiltered rows (debug
 * endpoints, backfill crons, dedup workers) must add an explicit comment:
 *   // intentionally unfiltered: <reason>
 */

// Structural/signal types that must NOT contribute to any conversion count.
// form_filled is "intent" tier; phone_input/phone_copy are "signal" tier --
// none are real conversions. phone_input/phone_copy canonicalize to
// "click_to_call" via canonicalType, which would inflate the completed-tier
// bucket. Defined here (not in site-tag-analytics.ts) so every conversion-
// reading path can import from a single, non-circular location.
export const EXCLUDED_CONVERSION_TYPES = [
  "form_iframe_present",
  "error_count_update",
  "form_filled",
  "phone_input",
  "phone_copy",
] as const;

export interface CountedWhereOpts {
  /** Include conversions at or after this timestamp */
  since?: Date;
  /** Include conversions at or before this timestamp */
  until?: Date;
  /**
   * Narrow to a specific subset of types (EXCLUDED_CONVERSION_TYPES are still
   * removed from the in-list so structural signals cannot leak through).
   */
  types?: string[];
  /**
   * When true, only rows with successConfirmed=true are included.
   * Set from TrackedSite.requireSuccessConfirmed. Default false (safe for all brands
   * that have not opted into the success-gating feature).
   */
  requireSuccessConfirmed?: boolean;
}

/**
 * Returns the canonical Prisma WHERE clause for counting real, unique,
 * user-facing conversions for a brand.
 *
 * Usage:
 *   await prisma.siteConversion.count({
 *     where: countedConversionWhere(brandId, { since: startDate }),
 *   });
 */
export function countedConversionWhere(brandId: string, opts: CountedWhereOpts = {}) {
  const { since, until, types, requireSuccessConfirmed = false } = opts;

  const excluded = EXCLUDED_CONVERSION_TYPES as readonly string[];
  const conversionTypeFilter =
    types && types.length > 0
      ? { in: types.filter((t) => !excluded.includes(t)) }
      : { notIn: [...EXCLUDED_CONVERSION_TYPES] as string[] };

  return {
    brandId,
    isDuplicateOf: null,
    invalidatedReason: null,
    conversionType: conversionTypeFilter,
    ...(since || until
      ? { timestamp: { ...(since ? { gte: since } : {}), ...(until ? { lte: until } : {}) } }
      : {}),
    ...(requireSuccessConfirmed ? { successConfirmed: true as const } : {}),
  };
}
