/**
 * Configuration for /createWO — ServiceChannel work order creation defaults.
 * Values can be overridden via environment variables; run GET /create-wo-discovery
 * (admin) to inspect recent tenant-specific field samples.
 */

function parseCsvEnv(name, fallback = []) {
  const raw = process.env[name];
  if (!raw || !String(raw).trim()) return [...fallback];
  return String(raw)
    .split(',')
    .map((s) => s.trim())
    .filter(Boolean);
}

function parseNumberEnv(name, fallback) {
  const raw = process.env[name];
  if (raw == null || raw === '') return fallback;
  const n = Number(raw);
  return Number.isFinite(n) ? n : fallback;
}

function parseBoolEnv(name, fallback = false) {
  const raw = process.env[name];
  if (raw == null || raw === '') return fallback;
  return /^(1|true|yes|on)$/i.test(String(raw).trim());
}

export function isWorkOrderCreateEnabled() {
  return parseBoolEnv('SC_CREATE_ENABLED', true);
}

export function getWorkOrderCreateConfig() {
  const providerId = parseNumberEnv(
    'SC_CREATE_DEFAULT_PROVIDER_ID',
    parseNumberEnv('SPACE_CLEANUP_PROVIDER_ID', 2000002215)
  );

  const issueAreaId = parseNumberEnv('SC_CREATE_ISSUE_AREA_ID', null);

  return {
    enabled: isWorkOrderCreateEnabled(),
    tradeName: process.env.SC_CREATE_DEFAULT_TRADE || 'AUDIO & VIDEO',
    providerId,
    providerName:
      process.env.SC_CREATE_DEFAULT_PROVIDER_NAME ||
      'Pro-Motion Technology Group, LLC',
    storePadLength: parseNumberEnv('SC_CREATE_STORE_PAD_LENGTH', 6),
    defaultCategory: process.env.SC_CREATE_DEFAULT_CATEGORY || 'REPAIR',
    defaultPriority: process.env.SC_CREATE_DEFAULT_PRIORITY || 'P24',
    defaultNte: parseNumberEnv('SC_CREATE_DEFAULT_NTE', 500),
    categories: parseCsvEnv('SC_CREATE_CATEGORIES', ['REPAIR', 'MAINTENANCE', 'PROJECT']),
    priorities: parseCsvEnv('SC_CREATE_PRIORITIES', [
      'P24',
      'P1 - 4 Hours',
      'P2 - 8 Hours',
      'P3 - 24 Hours',
      'P4 - 72 Hours',
    ]),
    problemCodes: parseCsvEnv('SC_CREATE_PROBLEM_CODES', [
      'Music completely out',
      'Needs service',
      'Partial Music',
    ]),
    requireIssueList: parseBoolEnv('SC_CREATE_REQUIRE_ISSUELIST', false),
    issueRequestInfo: issueAreaId
      ? {
          AreaId: issueAreaId,
          ExtendedAreaName: process.env.SC_CREATE_ISSUE_EXTENDED_AREA_NAME || '',
          ProblemType: process.env.SC_CREATE_ISSUE_PROBLEM_TYPE || '',
          AssetType: process.env.SC_CREATE_ISSUE_ASSET_TYPE || '',
        }
      : null,
    allowedPersonIds: parseCsvEnv('SC_CREATE_ALLOWED_PERSON_IDS', []),
  };
}

export function isPersonAllowedToCreateWorkOrder(personId, config = getWorkOrderCreateConfig()) {
  if (!config.allowedPersonIds.length) return true;
  return config.allowedPersonIds.includes(String(personId || '').trim());
}
