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/[name] — read a specific secret value */
export async function GET(_req: NextRequest, { params }: { params: Promise<{ name: string }> }) {
  try {
    const { name } = await params;
    const client = getSecretClient();
    const secret = await client.getSecret(name);

    return NextResponse.json({
      name: secret.name,
      value: secret.value,
      version: secret.properties.version,
      enabled: secret.properties.enabled,
      createdOn: secret.properties.createdOn?.toISOString(),
      updatedOn: secret.properties.updatedOn?.toISOString(),
      expiresOn: secret.properties.expiresOn?.toISOString() ?? null,
      contentType: secret.properties.contentType ?? null,
      tags: secret.properties.tags ?? {},
    });
  } catch (err) {
    const message = err instanceof Error ? err.message : String(err);
    const status = message.includes('NotFound') ? 404 : 500;
    return NextResponse.json({ error: message }, { status });
  }
}

/** DELETE /api/ops/secrets/[name] — soft-delete a secret */
export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ name: string }> }) {
  try {
    const { name } = await params;
    const client = getSecretClient();
    const poller = await client.beginDeleteSecret(name);
    await poller.pollUntilDone();

    return NextResponse.json({ deleted: true, name });
  } catch (err) {
    return NextResponse.json(
      { error: err instanceof Error ? err.message : String(err) },
      { status: 500 }
    );
  }
}
