/**
 * CPC-CSD permission service – API-driven access based on admin configuration.
 * Reads viewerEmails from CPC_CSD_ADMIN_CONFIG (legacy CPC_CDC_ADMIN_CONFIG until migrated).
 */

import { selectCpcCsdAdminConfigValue } from '../utils/cpcCsdAdminConfigDb';

export interface CpcCdcViewerConfig {
  viewerEmails: string[];
}

const emptyConfig: CpcCdcViewerConfig = {
  viewerEmails: [],
};

function normalizeEmail(email: string): string {
  return (email || '').trim().toLowerCase();
}

/**
 * Load CPC-CSD viewer config from admin_configurations.
 * Returns empty list if config is missing or invalid.
 */
export async function getCpcCdcViewerConfig(): Promise<CpcCdcViewerConfig> {
  try {
    const raw = await selectCpcCsdAdminConfigValue();
    if (!raw) {
      return emptyConfig;
    }

    const parsed = JSON.parse(raw);
    const viewerEmails = Array.isArray(parsed.viewerEmails)
      ? parsed.viewerEmails.map((e: unknown) => normalizeEmail(String(e ?? ''))).filter(Boolean)
      : [];

    return { viewerEmails };
  } catch {
    return emptyConfig;
  }
}

/**
 * Check if user can access CPC-CSD section.
 * - Admin: always allowed.
 * - Otherwise: only listed emails are allowed.
 */
export async function canAccessCpcCdc(userEmail: string, role?: string): Promise<boolean> {
  if (role === 'ADMIN') return true;

  const config = await getCpcCdcViewerConfig();
  const email = normalizeEmail(userEmail);
  if (!email) return false;
  return config.viewerEmails.includes(email);
}
