import { Buffer } from 'node:buffer';
import { NextResponse } from 'next/server';

export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';

const READONLY_ENABLED = process.env.IWOOOS_WAZUH_READONLY_ENABLED === 'true';
const WAZUH_API_BASE_URL = process.env.WAZUH_API_BASE_URL?.trim() ?? '';
const WAZUH_API_USERNAME = process.env.WAZUH_API_USERNAME?.trim() ?? '';
const WAZUH_API_PASSWORD = process.env.WAZUH_API_PASSWORD?.trim() ?? '';
const EXPECTED_MIN_AGENT_COUNT = parseExpectedMinAgentCount(
  process.env.IWOOOS_WAZUH_EXPECTED_MIN_AGENT_COUNT?.trim() ?? '',
);
const REQUEST_TIMEOUT_MS = 5000;

type WazuhConnectionSummary = {
  active?: number;
  disconnected?: number;
  never_connected?: number;
  pending?: number;
  total?: number;
}

type WazuhAgent = {
  id?: string;
  status?: string;
  os?: {
    name?: string;
    platform?: string;
  };
  lastKeepAlive?: string;
}

type WazuhApiEnvelope<T> = {
  data?: T;
}

function boundaryResponse(status: string, httpStatus = 200) {
  return NextResponse.json(
    {
      schema_version: 'iwooos_wazuh_readonly_status_v1',
      status,
      mode: 'metadata_only_no_active_response_no_raw_payload',
      configured: false,
      summary: {
        wazuh_platform_reported_count: 1,
        readonly_api_enabled_count: READONLY_ENABLED ? 1 : 0,
        wazuh_manager_query_accepted_count: 0,
        wazuh_event_accepted_count: 0,
        host_forensics_accepted_count: 0,
        active_response_authorized_count: 0,
        host_write_authorized_count: 0,
        runtime_gate_count: 0,
        expected_min_agent_count: EXPECTED_MIN_AGENT_COUNT,
        agent_registry_empty_count: 0,
        agent_below_expected_minimum_count: 0,
        agent_visibility_no_false_green_count: 1,
      },
      boundaries: {
        active_response_authorized: false,
        host_write_authorized: false,
        secret_value_collection_allowed: false,
        raw_wazuh_payload_storage_allowed: false,
        agent_identity_public_display_allowed: false,
        internal_ip_public_display_allowed: false,
        not_authorization: true,
      },
    },
    { status: httpStatus },
  );
}

async function fetchJson<T>(url: string, init: RequestInit): Promise<T> {
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
  try {
    const response = await fetch(url, { ...init, signal: controller.signal, cache: 'no-store' });
    if (!response.ok) {
      throw new Error(`Wazuh read-only request failed with status ${response.status}`);
    }
    return (await response.json()) as T;
  } finally {
    clearTimeout(timeout);
  }
}

function requireHttpsBaseUrl(value: string): URL | null {
  try {
    const url = new URL(value);
    return url.protocol === 'https:' ? url : null;
  } catch {
    return null;
  }
}

function parseExpectedMinAgentCount(value: string) {
  const parsed = Number.parseInt(value, 10);
  return Number.isFinite(parsed) ? Math.max(0, parsed) : 0;
}

function numberOrDefault(value: unknown, fallback: number) {
  return typeof value === 'number' && Number.isFinite(value) ? value : fallback;
}

function agentVisibilityStatus(agentTotal: number) {
  if (agentTotal <= 0) {
    return 'wazuh_agent_registry_empty';
  }
  if (EXPECTED_MIN_AGENT_COUNT > 0 && agentTotal < EXPECTED_MIN_AGENT_COUNT) {
    return 'wazuh_agent_registry_below_expected';
  }
  return 'readonly_metadata_available';
}

function redactedAgent(agent: WazuhAgent, index: number) {
  return {
    alias: `agent-${String(index + 1).padStart(2, '0')}`,
    status: agent.status ?? 'unknown',
    os: agent.os?.platform ?? agent.os?.name ?? 'unknown',
    last_seen_present: Boolean(agent.lastKeepAlive),
  };
}

export async function GET() {
  if (!READONLY_ENABLED) {
    return boundaryResponse('disabled_waiting_iwooos_wazuh_owner_gate');
  }

  const baseUrl = requireHttpsBaseUrl(WAZUH_API_BASE_URL);
  if (!baseUrl || !WAZUH_API_USERNAME || !WAZUH_API_PASSWORD) {
    return boundaryResponse('misconfigured_missing_server_side_wazuh_env', 503);
  }

  try {
    const authHeader = Buffer.from(`${WAZUH_API_USERNAME}:${WAZUH_API_PASSWORD}`, 'utf8').toString('base64');
    const auth = await fetchJson<WazuhApiEnvelope<{ token?: string }>>(
      new URL('/security/user/authenticate', baseUrl).toString(),
      {
        headers: {
          Authorization: `Basic ${authHeader}`,
        },
      },
    );
    const token = auth.data?.token;
    if (!token) {
      return boundaryResponse('wazuh_auth_token_missing', 502);
    }

    const [status, agents] = await Promise.all([
      fetchJson<WazuhApiEnvelope<{ connection?: WazuhConnectionSummary }>>(
        new URL('/agents/summary/status', baseUrl).toString(),
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      ),
      fetchJson<WazuhApiEnvelope<{ affected_items?: WazuhAgent[] }>>(
        new URL('/agents?limit=100&select=id,status,os.name,os.platform,lastKeepAlive', baseUrl).toString(),
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      ),
    ]);

    const affectedItems = agents.data?.affected_items ?? [];
    const connection = status.data?.connection ?? {};
    const agentTotal = numberOrDefault(connection.total, affectedItems.length);
    const agentActive = numberOrDefault(connection.active, 0);
    const agentDisconnected = numberOrDefault(connection.disconnected, 0);
    const agentPending = numberOrDefault(connection.pending, 0);
    const agentRegistryEmpty = agentTotal <= 0;
    const agentBelowExpected = EXPECTED_MIN_AGENT_COUNT > 0 && agentTotal < EXPECTED_MIN_AGENT_COUNT;

    return NextResponse.json({
      schema_version: 'iwooos_wazuh_readonly_status_v1',
      status: agentVisibilityStatus(agentTotal),
      mode: 'metadata_only_no_active_response_no_raw_payload',
      configured: true,
      summary: {
        wazuh_platform_reported_count: 1,
        readonly_api_enabled_count: 1,
        agent_total: agentTotal,
        agent_active: agentActive,
        agent_disconnected: agentDisconnected,
        agent_pending: agentPending,
        expected_min_agent_count: EXPECTED_MIN_AGENT_COUNT,
        agent_registry_empty_count: agentRegistryEmpty ? 1 : 0,
        agent_below_expected_minimum_count: agentBelowExpected ? 1 : 0,
        agent_visibility_no_false_green_count: 1,
        wazuh_manager_query_accepted_count: 0,
        wazuh_event_accepted_count: 0,
        host_forensics_accepted_count: 0,
        active_response_authorized_count: 0,
        host_write_authorized_count: 0,
        runtime_gate_count: 0,
      },
      agents: affectedItems.slice(0, 20).map(redactedAgent),
      boundaries: {
        active_response_authorized: false,
        host_write_authorized: false,
        secret_value_collection_allowed: false,
        raw_wazuh_payload_storage_allowed: false,
        agent_identity_public_display_allowed: false,
        internal_ip_public_display_allowed: false,
        not_authorization: true,
      },
    });
  } catch {
    return boundaryResponse('wazuh_readonly_metadata_unavailable', 502);
  }
}
