import type { SourceType, DocumentStatus, VerificationStatus, DocumentCategory } from '@/types/firestore';

/**
 * 공통 상수 및 유틸리티
 */

export const ADMIN_EMAILS: string[] = ['jonghyuk.jeon@gmail.com', 'drumbrab@gmail.com'];

/**
 * 작성자 이름 포맷팅 (내부 계정명 → 표시 이름 변환)
 */
export function formatAuthorName(name: string | null | undefined): string {
    if (!name) return '이름 없음';
    if (name === 'jonghyuk.jeon') return '전종혁';
    return name;
}

// ── 출처 필터 칩 매핑 ──────────────────────────
export const SOURCE_CHIP_MAP: Record<string, SourceType[] | null> = {
  '전체': null,
  '약관': ['policy_pdf'],
  '전문가': ['newsletter', 'wiki_editorial', 'kakao_expert'],
  '커뮤니티': ['youtube', 'kakao_community', 'user_submitted'],
};

export const SOURCE_CHIP_KEYS = Object.keys(SOURCE_CHIP_MAP) as (keyof typeof SOURCE_CHIP_MAP)[];

// ── sourceType → authorityTier 기본 매핑 ────────
const TIER_MAP: Record<SourceType, number> = {
  policy_pdf: 1,
  regulation: 1.5,
  newsletter: 2,
  court_ruling: 2,
  wiki_editorial: 3,
  kakao_expert: 3.5,
  kakao_community: 4,
  youtube: 4,
  user_submitted: 4,
  dashboard_insight: 3,
};

export function getDefaultAuthorityTier(sourceType: SourceType): number {
  return TIER_MAP[sourceType];
}

// ── authorityTier → 배지 정보 ───────────────────
export interface BadgeInfo {
  label: string;
  colorClass: string;
  icon: string;
}

export function getAuthorityBadgeInfo(authorityTier?: number, sourceType?: SourceType): BadgeInfo {
  if (!authorityTier && !sourceType) {
    return { label: '일반', colorClass: 'bg-gray-100 text-gray-600 border-gray-200', icon: '📝' };
  }
  const tier = authorityTier ?? (sourceType ? getDefaultAuthorityTier(sourceType) : 4);

  if (tier <= 1.5) {
    return { label: tier === 1 ? '약관' : '금감원', colorClass: 'bg-blue-50 text-blue-700 border-blue-200', icon: '🛡️' };
  }
  if (tier <= 3.5) {
    return { label: '전문가', colorClass: 'bg-emerald-50 text-emerald-700 border-emerald-200', icon: '✅' };
  }
  return { label: '참고용', colorClass: 'bg-gray-100 text-gray-500 border-gray-200', icon: '💬' };
}

// ── sourceType → 한글 라벨 ──────────────────────
export const SOURCE_TYPE_LABEL: Record<SourceType, string> = {
  policy_pdf: '약관 원문',
  regulation: '금감원/보험업법',
  newsletter: '소식지',
  court_ruling: '판례',
  wiki_editorial: '위키 편집',
  kakao_expert: '전문가 단톡',
  kakao_community: '커뮤니티 단톡',
  youtube: '유튜브',
  user_submitted: '사용자 제출',
  dashboard_insight: '대시보드 인사이트',
};

// ── verificationStatus → 한글 라벨 ─────────────
export const VERIFICATION_LABEL: Record<string, { label: string; colorClass: string }> = {
  unverified: { label: '미검증', colorClass: 'text-amber-600 bg-amber-50' },
  auto_passed: { label: '자동 검증', colorClass: 'text-blue-600 bg-blue-50' },
  expert_verified: { label: '✓ 전문가 검증', colorClass: 'text-emerald-600 bg-emerald-50' },
};

// ── Phase 2a: 신뢰도 매핑 ───────────────────────

export type TrustLevel = 'official' | 'expert' | 'reference';

/**
 * authorityTier와 sourceType으로 신뢰등급 판정
 * tier <= 1.5 → 'official', tier <= 3.5 → 'expert', 그 외 → 'reference'
 */
export function getTrustLevel(authorityTier?: number, sourceType?: SourceType): TrustLevel {
  if (authorityTier === undefined && sourceType === undefined) return 'reference';
  const tier = authorityTier ?? (sourceType ? getDefaultAuthorityTier(sourceType) : 4);
  if (tier <= 1.5) return 'official';
  if (tier <= 3.5) return 'expert';
  return 'reference';
}

export interface TrustBadgeInfo {
  level: TrustLevel;
  label: string;
  colorClass: string;
}

export function getTrustBadgeInfo(authorityTier?: number, sourceType?: SourceType): TrustBadgeInfo {
  const level = getTrustLevel(authorityTier, sourceType);
  switch (level) {
    case 'official':
      return { level, label: '공식확인', colorClass: 'bg-green-50 text-green-800 border-green-300' };
    case 'expert':
      return { level, label: '전문가검증', colorClass: 'bg-blue-50 text-blue-800 border-blue-300' };
    case 'reference':
      return { level, label: '참고정보', colorClass: 'bg-gray-100 text-gray-700 border-gray-300' };
  }
}

export type VerificationVisualState = 'pending' | 'in_review' | 'verified' | 'rejected';

export function getVerificationVisualState(
  documentStatus?: DocumentStatus,
  verificationStatus?: VerificationStatus,
): VerificationVisualState {
  if (documentStatus === 'approved' || verificationStatus === 'expert_verified' || verificationStatus === 'auto_passed') return 'verified';
  if (documentStatus === 'rejected' || documentStatus === 'revision_requested') return 'rejected';
  if (documentStatus === 'in_review' || documentStatus === 'needs_re_review') return 'in_review';
  return 'pending';
}

export type BannerSeverity = 'info' | 'caution';

export function getAutoSeverity(category?: DocumentCategory, sourceType?: SourceType): BannerSeverity {
  if (category === 'practice' && sourceType === 'user_submitted') return 'caution';
  return 'info';
}
