/**
 * get-dns-zones — list DNS zones + forwarders + conditional forwarders +
 * recent zone-transfer status. Site-anchored.
 *
 * Useful for documenting which zones each DC is authoritative for and
 * verifying forwarders match what's recorded on the firewall Configuration.
 */

import { type RmmScript, parseJsonOutput } from './types';

export const getDnsZones: RmmScript = {
  id: 'get-dns-zones',
  name: 'DNS zones + forwarders',
  description:
    'For every DC in the domain: zones, zone type, dynamic update mode, forwarders + conditional forwarders.',
  target_type: 'site_anchor',
  expected_runtime_seconds: 60,
  version: 1,
  body: `
$ErrorActionPreference = 'SilentlyContinue'
Import-Module ActiveDirectory -ErrorAction SilentlyContinue
Import-Module DnsServer -ErrorAction SilentlyContinue

$dcs = Get-ADDomainController -Filter * | Select-Object -ExpandProperty HostName

$result = foreach ($dc in $dcs) {
  $zones = Get-DnsServerZone -ComputerName $dc -ErrorAction SilentlyContinue |
    Select-Object ZoneName, ZoneType, IsDsIntegrated, DynamicUpdate, IsAutoCreated, IsReverseLookupZone
  $fwd = (Get-DnsServerForwarder -ComputerName $dc -ErrorAction SilentlyContinue) |
    Select-Object @{n='ip';e={$_.IPAddress -join ','}}, Timeout, UseRootHint
  $cfwd = Get-DnsServerZone -ComputerName $dc -ErrorAction SilentlyContinue |
    Where-Object { $_.ZoneType -eq 'Forwarder' } |
    Select-Object ZoneName, @{n='masters';e={ ($_.MasterServers | ForEach-Object { $_.IPAddressToString }) -join ',' }}
  [pscustomobject]@{
    dc = $dc
    zones = $zones
    forwarders = $fwd
    conditional_forwarders = $cfwd
  }
}

@{
  hostname = $env:COMPUTERNAME
  captured_at_utc = (Get-Date).ToUniversalTime().ToString("o")
  dcs = $result
} | ConvertTo-Json -Depth 6 -Compress
`.trim(),
  parseOutput: (stdout) => parseJsonOutput(stdout),
};
