/**
 * CPC/CSD document module — admin_configurations keys for viewer allow-list.
 * Legacy key kept for reads until migrated or overwritten by admin save.
 */
import { QueryTypes } from 'sequelize';
import { sequelize } from '../config/database';

export const CPC_CSD_ADMIN_CONFIG_KEY = 'CPC_CSD_ADMIN_CONFIG';
export const CPC_CDC_ADMIN_CONFIG_KEY_LEGACY = 'CPC_CDC_ADMIN_CONFIG';

/** Prefer CPC_CSD_ADMIN_CONFIG row; fall back to legacy CPC_CDC_ADMIN_CONFIG if present. */
export async function selectCpcCsdAdminConfigValue(): Promise<string | null> {
  const result = await sequelize.query<{ config_value: string }>(
    `SELECT config_value FROM admin_configurations
     WHERE config_key IN (:kCsd, :kLegacy)
     ORDER BY CASE WHEN config_key = :kCsd THEN 0 ELSE 1 END
     LIMIT 1`,
    {
      replacements: { kCsd: CPC_CSD_ADMIN_CONFIG_KEY, kLegacy: CPC_CDC_ADMIN_CONFIG_KEY_LEGACY },
      type: QueryTypes.SELECT,
    }
  );
  if (!result?.length || !result[0].config_value) return null;
  return result[0].config_value;
}
