import 'server-only';

import { z } from 'zod';

const booleanText = z
  .enum(['true', 'false'])
  .default('false')
  .transform((value) => value === 'true');

const environmentSchema = z.object({
  NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
  NEXT_PUBLIC_DEMO_ENABLED: booleanText,
  DEMO_SUBMISSION_MODE: z.enum(['blocked', 'local']).default('blocked'),
  DEMO_REQUEST_TIMEOUT_MS: z.coerce.number().int().min(250).max(15_000).default(4_000),
  DEMO_IDEMPOTENCY_TTL_SECONDS: z.coerce.number().int().min(60).max(86_400).default(900),
  DEMO_TEST_SCENARIOS_ENABLED: booleanText,
  DEMO_LOCAL_TEST_MODE: booleanText,
  NEXT_PUBLIC_ANALYTICS_MODE: z.enum(['disabled', 'test']).default('disabled'),
  SITE_ORIGIN: z.string().url().optional(),
});

export type IntegrationEnvironment = z.infer<typeof environmentSchema>;

export interface EnvironmentValidationResult {
  ok: boolean;
  errors: string[];
  environment?: IntegrationEnvironment;
}

export function validateIntegrationEnvironment(
  source: NodeJS.ProcessEnv = process.env,
): EnvironmentValidationResult {
  const inferredNodeEnv =
    source.NODE_ENV === 'production' || source.NODE_ENV === 'test'
      ? source.NODE_ENV
      : 'development';
  const normalizedSource = {
    ...source,
    DEMO_SUBMISSION_MODE:
      source.DEMO_SUBMISSION_MODE ?? (inferredNodeEnv === 'production' ? 'blocked' : 'local'),
  };
  const parsed = environmentSchema.safeParse(normalizedSource);
  if (!parsed.success) {
    return {
      ok: false,
      errors: parsed.error.issues.map((issue) => `${issue.path.join('.')}: ${issue.message}`),
    };
  }

  const environment = parsed.data;
  const errors: string[] = [];
  const localTestOrigin =
    environment.SITE_ORIGIN &&
    ['127.0.0.1', 'localhost'].includes(new URL(environment.SITE_ORIGIN).hostname);
  const productionLocalTest =
    environment.NODE_ENV === 'production' && environment.DEMO_LOCAL_TEST_MODE && localTestOrigin;
  if (
    environment.NODE_ENV === 'production' &&
    environment.NEXT_PUBLIC_DEMO_ENABLED &&
    !productionLocalTest
  ) {
    errors.push(
      'NEXT_PUBLIC_DEMO_ENABLED must remain false until an approved production lead adapter and legal consent decision are implemented.',
    );
  }
  if (
    environment.NODE_ENV === 'production' &&
    environment.DEMO_SUBMISSION_MODE === 'local' &&
    !productionLocalTest
  ) {
    errors.push(
      'DEMO_SUBMISSION_MODE=local is prohibited outside an explicit loopback test runtime.',
    );
  }
  if (
    environment.NODE_ENV === 'production' &&
    environment.DEMO_TEST_SCENARIOS_ENABLED &&
    !productionLocalTest
  ) {
    errors.push(
      'DEMO_TEST_SCENARIOS_ENABLED is prohibited outside an explicit loopback test runtime.',
    );
  }
  if (
    environment.NODE_ENV === 'production' &&
    environment.NEXT_PUBLIC_ANALYTICS_MODE !== 'disabled'
  ) {
    errors.push('Analytics must remain disabled until provider and consent approval are recorded.');
  }

  return errors.length > 0 ? { ok: false, errors, environment } : { ok: true, errors, environment };
}

export function getIntegrationEnvironment(): IntegrationEnvironment {
  const result = validateIntegrationEnvironment();
  if (!result.ok || !result.environment) {
    throw new Error(`Invalid Phase 14 integration environment: ${result.errors.join(' | ')}`);
  }
  return result.environment;
}

export interface PublicIntegrationConfig {
  demoSubmissionEnabled: boolean;
  demoMode: 'blocked' | 'local';
  analyticsMode: 'disabled' | 'test';
}

export function getPublicIntegrationConfig(): PublicIntegrationConfig {
  const environment = getIntegrationEnvironment();
  const developmentDefault = environment.NODE_ENV !== 'production';
  const demoSubmissionEnabled =
    environment.DEMO_SUBMISSION_MODE === 'local' &&
    (environment.NEXT_PUBLIC_DEMO_ENABLED || developmentDefault);
  return {
    demoSubmissionEnabled,
    demoMode: demoSubmissionEnabled ? 'local' : 'blocked',
    analyticsMode: environment.NEXT_PUBLIC_ANALYTICS_MODE,
  };
}
