/**
 * Shared domain-attach workflow used by the REST endpoint and the MCP tool.
 *
 * Extracted from the route handler so there's exactly one code path that
 * writes DNS, updates the registrar, mutates Coolify, and persists the
 * vibn_domains row. All failures are `AttachError` with a status + tag
 * the caller can map to an HTTP response.
 */

import {
  getApplicationInProject,
  listServers,
  setApplicationDomains,
  TenantError,
} from '@/lib/coolify';
import { cloudDnsProvider } from '@/lib/dns/cloud-dns';
import type { DnsRecord } from '@/lib/dns/provider';
import {
  markDomainAttached,
  recordDomainEvent,
  type VibnDomain,
} from '@/lib/domains';
import { setDomainLock, updateDomainNameservers, OpenSrsError } from '@/lib/opensrs';
import { parseDomainsString } from '@/lib/naming';
import type { VibnWorkspace } from '@/lib/workspaces';

export interface AttachInput {
  appUuid?: string;
  ip?: string;
  cname?: string;
  subdomains?: string[];
  updateRegistrarNs?: boolean;
}

export interface AttachResult {
  domain: VibnDomain;
  zone: { apex: string; zoneId: string; nameservers: string[] };
  records: Array<{ name: string; type: string; rrdatas: string[] }>;
  registrarNsUpdate: { responseCode: string; responseText: string } | null;
  coolifyUpdate: { appUuid: string; domains: string[] } | null;
}

/**
 * Status codes follow the HTTP convention so callers can pass them straight
 * to NextResponse.
 */
export class AttachError extends Error {
  constructor(
    public readonly status: number,
    public readonly tag: string,
    message: string,
    public readonly extra?: Record<string, unknown>,
  ) {
    super(message);
    this.name = 'AttachError';
  }
}

const DEFAULT_SUBS = ['@', 'www'];

export async function attachDomain(
  workspace: VibnWorkspace,
  domainRow: VibnDomain,
  input: AttachInput,
): Promise<AttachResult> {
  if (domainRow.status !== 'active') {
    throw new AttachError(409, 'not_active', `Domain is not active (status=${domainRow.status})`);
  }
  if (!input.appUuid && !input.ip && !input.cname) {
    throw new AttachError(400, 'no_target', 'One of `appUuid`, `ip`, or `cname` is required');
  }

  const apex = domainRow.domain;
  const subs = normalizeSubdomains(input.subdomains);
  if (subs.length === 0) {
    throw new AttachError(400, 'no_subdomains', '`subdomains` must contain at least one entry');
  }

  // Resolve the upstream target
  let targetIps: string[] | null = null;
  let targetCname: string | null = null;
  let coolifyAppUuid: string | null = null;

  if (input.appUuid) {
    if (!workspace.coolify_project_uuid) {
      throw new AttachError(503, 'no_project', 'Workspace has no Coolify project yet');
    }
    try {
      await getApplicationInProject(input.appUuid, workspace.coolify_project_uuid);
    } catch (err) {
      if (err instanceof TenantError) {
        throw new AttachError(403, 'tenant_mismatch', err.message);
      }
      throw new AttachError(404, 'app_not_found', 'Coolify app not found in this workspace');
    }
    coolifyAppUuid = input.appUuid;

    const serverUuid = workspace.coolify_server_uuid;
    if (!serverUuid) {
      throw new AttachError(503, 'no_server', 'Workspace has no Coolify server — cannot resolve public IP');
    }
    const servers = await listServers();
    const server = servers.find(s => s.uuid === serverUuid);
    if (!server || !server.ip) {
      throw new AttachError(502, 'server_ip_unknown', `Coolify server ${serverUuid} has no public IP`);
    }
    targetIps = [server.ip];
  } else if (input.ip) {
    if (!/^\d{1,3}(\.\d{1,3}){3}$/.test(input.ip)) {
      throw new AttachError(400, 'bad_ip', '`ip` must be a valid IPv4 address');
    }
    targetIps = [input.ip];
  } else if (input.cname) {
    const cname = input.cname.trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/+$/, '');
    if (!/^[a-z0-9-]+(\.[a-z0-9-]+)+$/i.test(cname)) {
      throw new AttachError(400, 'bad_cname', '`cname` must be a valid hostname');
    }
    targetCname = cname.endsWith('.') ? cname : `${cname}.`;
    if (subs.includes('@')) {
      throw new AttachError(400, 'cname_apex', 'CNAME on apex (@) is not allowed — use `ip` for the apex');
    }
  }

  // 1. Ensure Cloud DNS zone exists
  let zone;
  try {
    zone = await cloudDnsProvider.createZone(apex);
  } catch (err) {
    throw new AttachError(502, 'zone_create_failed', err instanceof Error ? err.message : String(err));
  }

  // 2. Write rrsets
  const records: DnsRecord[] = subs.flatMap<DnsRecord>(sub => {
    if (targetIps) return [{ name: sub, type: 'A', rrdatas: targetIps, ttl: 300 }];
    if (targetCname) return [{ name: sub, type: 'CNAME', rrdatas: [targetCname], ttl: 300 }];
    return [];
  });

  try {
    await cloudDnsProvider.setRecords(apex, records);
  } catch (err) {
    throw new AttachError(502, 'rrset_write_failed', err instanceof Error ? err.message : String(err));
  }

  // 3. Registrar-side nameserver update
  //
  // Some TLDs reject NS changes while the domain is locked (response 405).
  // We unlock → update NS → relock so the end state is "locked with the
  // right nameservers". If the initial NS update returns 405 we retry once
  // with the unlock sandwich.
  let registrarNsUpdate: { responseCode: string; responseText: string } | null = null;
  const updateNs = input.updateRegistrarNs !== false;
  if (updateNs && zone.nameservers.length >= 2) {
    try {
      registrarNsUpdate = await updateDomainNameservers(apex, zone.nameservers);
    } catch (err) {
      const locked405 =
        err instanceof OpenSrsError &&
        err.code === '405' &&
        /status prohibits operation/i.test(err.message);
      if (!locked405) {
        if (err instanceof OpenSrsError) {
          throw new AttachError(
            502,
            'registrar_ns_failed',
            `Registrar NS update failed (${err.code}): ${err.message}`,
            { zone: { apex, zoneId: zone.zoneId, nameservers: zone.nameservers } },
          );
        }
        throw new AttachError(502, 'registrar_ns_failed', err instanceof Error ? err.message : String(err));
      }
      // Locked → unlock, update, relock.
      try {
        await setDomainLock(apex, false);
        registrarNsUpdate = await updateDomainNameservers(apex, zone.nameservers);
      } catch (retryErr) {
        throw new AttachError(
          502,
          'registrar_ns_failed',
          `Registrar NS retry failed: ${retryErr instanceof Error ? retryErr.message : String(retryErr)}`,
          { zone: { apex, zoneId: zone.zoneId, nameservers: zone.nameservers } },
        );
      } finally {
        // Best-effort relock — if this fails we log but don't fail the attach.
        try {
          await setDomainLock(apex, true);
        } catch (relockErr) {
          console.warn('[attach] relock failed for', apex, relockErr);
        }
      }
    }
  }

  // 4. Coolify domain list
  let coolifyUpdate: { appUuid: string; domains: string[] } | null = null;
  if (coolifyAppUuid && workspace.coolify_project_uuid) {
    try {
      const app = await getApplicationInProject(coolifyAppUuid, workspace.coolify_project_uuid);
      const current = parseDomainsString(app.domains ?? app.fqdn ?? '');
      const toAdd = subs.map(s => (s === '@' ? apex : `${s}.${apex}`));
      const merged = uniq([...current, ...toAdd]);
      await setApplicationDomains(coolifyAppUuid, merged, { forceOverride: true });
      coolifyUpdate = { appUuid: coolifyAppUuid, domains: merged };
    } catch (err) {
      throw new AttachError(
        502,
        'coolify_domains_failed',
        `DNS is wired but Coolify domain-list update failed: ${err instanceof Error ? err.message : String(err)}`,
        { zone: { apex, zoneId: zone.zoneId, nameservers: zone.nameservers } },
      );
    }
  }

  // 5. Persist + event
  const updated = await markDomainAttached({
    domainId: domainRow.id,
    dnsProvider: cloudDnsProvider.id,
    dnsZoneId: zone.zoneId,
    dnsNameservers: zone.nameservers,
  });

  await recordDomainEvent({
    domainId: domainRow.id,
    workspaceId: workspace.id,
    type: 'attach.success',
    payload: {
      zone: zone.zoneId,
      nameservers: zone.nameservers,
      records: records.map(r => ({ name: r.name, type: r.type, rrdatas: r.rrdatas })),
      coolifyAppUuid,
      registrarNsUpdate,
    },
  });

  return {
    domain: updated,
    zone,
    records: records.map(r => ({ name: r.name, type: r.type, rrdatas: r.rrdatas })),
    registrarNsUpdate,
    coolifyUpdate,
  };
}

function normalizeSubdomains(input?: string[]): string[] {
  const raw = input && input.length > 0 ? input : DEFAULT_SUBS;
  const out: string[] = [];
  for (const s of raw) {
    if (typeof s !== 'string') continue;
    const clean = s.trim().toLowerCase();
    if (!clean) continue;
    if (clean === '@' || /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/.test(clean)) {
      out.push(clean);
    }
  }
  return uniq(out);
}

function uniq<T>(xs: T[]): T[] {
  return Array.from(new Set(xs));
}
