/**
 * 규정 변경 감지 순수 로직
 *
 * Firebase 의존 없음 → 단위 테스트 용이
 */

export interface RegulationChangeResult {
  shouldReReview: boolean;
  reason: string;
}

const REGULATION_SOURCE_TYPES = ['regulation', 'policy_pdf'] as const;
const TRACKED_FIELDS = ['sourceMeta', 'sourceUrl', 'regulationId', 'effectiveDate'] as const;

/**
 * 규정 변경 감지
 *
 * - sourceType이 'regulation' 또는 'policy_pdf'가 아니면 → not_regulation
 * - TRACKED_FIELDS 중 하나라도 변경되면 → shouldReReview: true
 * - 변경 없으면 → no_regulation_change
 */
export function detectRegulationChange(
  beforeData: Record<string, unknown>,
  afterData: Record<string, unknown>
): RegulationChangeResult {
  const sourceType = afterData.sourceType as string | undefined;

  if (
    !sourceType ||
    !(REGULATION_SOURCE_TYPES as readonly string[]).includes(sourceType)
  ) {
    return { shouldReReview: false, reason: 'not_regulation' };
  }

  for (const field of TRACKED_FIELDS) {
    const before = JSON.stringify(beforeData[field] ?? null);
    const after = JSON.stringify(afterData[field] ?? null);
    if (before !== after) {
      return {
        shouldReReview: true,
        reason: `규정 메타데이터 변경: ${field}`,
      };
    }
  }

  return { shouldReReview: false, reason: 'no_regulation_change' };
}
