/**
 * GET /api/route53/zones — list mirrored Route 53 hosted zones.
 *   requireAuth() gated.
 */

import { NextResponse } from 'next/server';
import { requireAuth } from '@/lib/auth-utils';
import postgresClient from '@/lib/services/postgres-client';
import type { Route53Zone } from '@/lib/types/route53';

interface ZoneRow {
  id: string;
  name: string;
  comment: string | null;
  private_zone: boolean;
  record_count: number;
  authoritative_name_servers: string[] | null;
  synced_at: string;
}

export async function GET() {
  const { error } = await requireAuth();
  if (error) return error;

  try {
    const res = await postgresClient.query<ZoneRow>(
      `SELECT id, name, comment, private_zone, record_count, authoritative_name_servers, synced_at
         FROM route53_zones
        WHERE is_deleted = false
        ORDER BY name`
    );

    const zones: Route53Zone[] = res.rows.map((row) => ({
      id: row.id,
      name: row.name,
      comment: row.comment,
      privateZone: row.private_zone,
      recordCount: row.record_count,
      authoritativeNameServers: row.authoritative_name_servers,
      syncedAt: row.synced_at,
      isDeleted: false,
    }));

    return NextResponse.json({ items: zones });
  } catch (err) {
    console.error('[ROUTE53-ZONES] Failed to list zones:', err);
    return NextResponse.json(
      { error: err instanceof Error ? err.message : 'Failed to fetch Route 53 zones' },
      { status: 500 }
    );
  }
}
