import dns from 'dns';
import {
  activateCustomDomain,
  getAllPendingCustomDomains,
} from './db.js';
import { logger } from './logger.js';

const VERIFY_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes
const STARTUP_DELAY_MS = 30_000;

export function startDomainVerifier(
  onDomainActivated: (tenantId: string) => Promise<void>,
): void {
  const check = async () => {
    const pending = getAllPendingCustomDomains();
    for (const row of pending) {
      try {
        const records = await dns.promises.resolveTxt(
          `_nanoclaw-verify.${row.domain}`,
        );
        const flat = records.flat();
        if (flat.includes(row.verification_token)) {
          activateCustomDomain(row.domain);
          logger.info(
            { domain: row.domain, tenantId: row.tenant_id },
            'Custom domain verified via DNS TXT — activating',
          );
          await onDomainActivated(row.tenant_id);
        }
      } catch {
        // DNS lookup failure or no TXT record — normal for pending domains
      }
    }
    setTimeout(check, VERIFY_INTERVAL_MS);
  };

  setTimeout(check, STARTUP_DELAY_MS);
  logger.info('Domain verifier started (DNS TXT polling every 5 minutes)');
}
