import { NextRequest, NextResponse } from 'next/server';
import { DefaultAzureCredential } from '@azure/identity';
import { SecretClient } from '@azure/keyvault-secrets';

export const dynamic = 'force-dynamic';

function getSecretClient(): SecretClient {
  const vaultUrl = process.env.AZURE_KEYVAULT_URL;
  if (!vaultUrl) {
    throw new Error('AZURE_KEYVAULT_URL is not configured');
  }
  return new SecretClient(vaultUrl, new DefaultAzureCredential());
}

/** GET /api/ops/secrets — list all secrets with metadata */
export async function GET() {
  try {
    const client = getSecretClient();
    const secrets: Array<{
      name: string;
      enabled: boolean;
      createdOn: string | null;
      updatedOn: string | null;
      expiresOn: string | null;
      contentType: string | null;
      tags: Record<string, string>;
    }> = [];

    for await (const properties of client.listPropertiesOfSecrets()) {
      secrets.push({
        name: properties.name,
        enabled: properties.enabled ?? true,
        createdOn: properties.createdOn?.toISOString() ?? null,
        updatedOn: properties.updatedOn?.toISOString() ?? null,
        expiresOn: properties.expiresOn?.toISOString() ?? null,
        contentType: properties.contentType ?? null,
        tags: properties.tags ?? {},
      });
    }

    // Sort alphabetically
    secrets.sort((a, b) => a.name.localeCompare(b.name));

    return NextResponse.json({
      vaultUrl: process.env.AZURE_KEYVAULT_URL,
      count: secrets.length,
      secrets,
    });
  } catch (err) {
    return NextResponse.json(
      { error: err instanceof Error ? err.message : String(err) },
      { status: 500 }
    );
  }
}

/** POST /api/ops/secrets — set or update a secret */
export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const { name, value, contentType, expiresOn, tags } = body as {
      name: string;
      value: string;
      contentType?: string;
      expiresOn?: string;
      tags?: Record<string, string>;
    };

    if (!name || !value) {
      return NextResponse.json({ error: 'name and value are required' }, { status: 400 });
    }

    const client = getSecretClient();
    const result = await client.setSecret(name, value, {
      contentType,
      expiresOn: expiresOn ? new Date(expiresOn) : undefined,
      tags,
    });

    return NextResponse.json({
      name: result.name,
      createdOn: result.properties.createdOn?.toISOString(),
      updatedOn: result.properties.updatedOn?.toISOString(),
      version: result.properties.version,
    });
  } catch (err) {
    return NextResponse.json(
      { error: err instanceof Error ? err.message : String(err) },
      { status: 500 }
    );
  }
}
