/**
 * GET /api/workspaces/[slug]/domains/[domain]
 *
 * Returns the full domain record (sans encrypted registrar password) plus
 * recent lifecycle events. Used by the UI and agents to check status after
 * a register call.
 */

import { NextResponse } from 'next/server';
import { requireWorkspacePrincipal } from '@/lib/auth/workspace-auth';
import { query } from '@/lib/db-postgres';
import { getDomainForWorkspace } from '@/lib/domains';

export async function GET(
  request: Request,
  { params }: { params: Promise<{ slug: string; domain: string }> },
) {
  const { slug, domain } = await params;
  const principal = await requireWorkspacePrincipal(request, { targetSlug: slug });
  if (principal instanceof NextResponse) return principal;

  const row = await getDomainForWorkspace(principal.workspace.id, decodeURIComponent(domain));
  if (!row) {
    return NextResponse.json({ error: 'Domain not found in this workspace' }, { status: 404 });
  }

  const events = await query<{
    id: string;
    type: string;
    payload: Record<string, unknown>;
    created_at: Date;
  }>(
    `SELECT id, type, payload, created_at
       FROM vibn_domain_events
      WHERE domain_id = $1
      ORDER BY created_at DESC
      LIMIT 20`,
    [row.id],
  );

  return NextResponse.json({
    id: row.id,
    domain: row.domain,
    tld: row.tld,
    status: row.status,
    registrar: row.registrar,
    registrarOrderId: row.registrar_order_id,
    registrarUsername: row.registrar_username,
    periodYears: row.period_years,
    whoisPrivacy: row.whois_privacy,
    autoRenew: row.auto_renew,
    registeredAt: row.registered_at,
    expiresAt: row.expires_at,
    dnsProvider: row.dns_provider,
    dnsZoneId: row.dns_zone_id,
    dnsNameservers: row.dns_nameservers,
    pricePaidCents: row.price_paid_cents,
    priceCurrency: row.price_currency,
    createdAt: row.created_at,
    updatedAt: row.updated_at,
    events,
  });
}
