/**
 * DELETE /api/projects/[projectId]/secrets/[key]
 * GET    /api/projects/[projectId]/secrets/[key]  — reveal (decrypted)
 *
 * Reveal is intentionally project-scoped (user must own the project).
 * Never log the plaintext value.
 */
import { NextResponse } from "next/server";
import { query, queryOne } from "@/lib/db-postgres";
import { withTenantProject } from "@/lib/server/api-handler";
import { decryptSecret } from "@/lib/auth/secret-box";
import { log } from "@/lib/server/logger";

export const DELETE = withTenantProject(
  async (_req, ctx, { project }) => {
    const { key } = await (ctx.params as Promise<{ projectId: string; key: string }>);
    await query(
      `DELETE FROM fs_project_secrets WHERE project_id = $1 AND key = $2`,
      [project.id, key],
    );
    log.info("project secret deleted", {
      route: "api.projects.secrets.delete",
      projectId: project.id,
      key,
    });
    return NextResponse.json({ ok: true });
  },
);

export const GET = withTenantProject(
  async (_req, ctx, { project }) => {
    const { key } = await (ctx.params as Promise<{ projectId: string; key: string }>);
    const row = await queryOne<{ value_enc: string }>(
      `SELECT value_enc FROM fs_project_secrets WHERE project_id = $1 AND key = $2`,
      [project.id, key],
    );
    if (!row) {
      return NextResponse.json({ error: "Secret not found" }, { status: 404 });
    }
    try {
      const value = decryptSecret(row.value_enc);
      return NextResponse.json({ key, value });
    } catch {
      return NextResponse.json(
        { error: "Decryption failed — VIBN_SECRETS_KEY may have rotated" },
        { status: 500 },
      );
    }
  },
);
