import { NextRequest, NextResponse } from "next/server";
import https from "node:https";
import fs from "node:fs";
import { requireAuth } from "@/auth";

const OPS_API_URL = process.env.OPS_API_URL || "https://172.17.8.20:8443";
const OPS_API_KEY = process.env.OPS_API_KEY || "";

let _tlsAgent: https.Agent | null = null;
function getTlsAgent(): https.Agent {
  if (!_tlsAgent) {
    _tlsAgent = new https.Agent({
      cert: fs.readFileSync("/etc/mcp-certs/client.crt"),
      key: fs.readFileSync("/etc/mcp-certs/client.key"),
      ca: fs.readFileSync("/etc/mcp-certs/ca-chain.crt"),
      rejectUnauthorized: false,
    });
  }
  return _tlsAgent;
}

function opsApiFetch(
  path: string,
  method: string = "GET",
  body?: string
): Promise<{ status: number; data: string }> {
  const url = new URL(`${OPS_API_URL}${path}`);
  return new Promise((resolve, reject) => {
    const req = https.request(
      {
        hostname: url.hostname,
        port: url.port,
        path: url.pathname + url.search,
        method,
        agent: getTlsAgent(),
        headers: {
          "X-API-Key": OPS_API_KEY,
          "Content-Type": "application/json",
        },
      },
      (res) => {
        const chunks: Buffer[] = [];
        res.on("data", (chunk) => chunks.push(chunk));
        res.on("end", () =>
          resolve({
            status: res.statusCode ?? 500,
            data: Buffer.concat(chunks).toString(),
          })
        );
      }
    );
    req.on("error", reject);
    if (body) req.write(body);
    req.end();
  });
}

export async function GET() {
  try {
    const user = await requireAuth();
    const userId = user.gscUserId;
    const tenantId = user.tenantId;
    if (!userId || !tenantId) {
      return NextResponse.json(null);
    }

    const res = await opsApiFetch(
      `/api/v1/agents/me?userId=${userId}&tenantId=${tenantId}`
    );

    if (res.status >= 400) {
      return NextResponse.json(null);
    }

    const envelope = JSON.parse(res.data);
    return NextResponse.json(envelope.data?.config ?? null);
  } catch {
    return NextResponse.json(null, { status: 401 });
  }
}

export async function PUT(req: NextRequest) {
  try {
    const user = await requireAuth();
    const userId = user.gscUserId;
    const tenantId = user.tenantId;
    if (!userId || !tenantId) {
      return NextResponse.json(
        { error: "Missing user identity" },
        { status: 400 }
      );
    }

    const body = await req.json();

    const res = await opsApiFetch(
      "/api/v1/agents/me",
      "PUT",
      JSON.stringify({ userId, tenantId, config: body })
    );

    if (res.status >= 400) {
      return NextResponse.json({ error: res.data }, { status: res.status });
    }

    const envelope = JSON.parse(res.data);
    return NextResponse.json(envelope.data?.config ?? null);
  } catch {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
}

export async function DELETE() {
  try {
    const user = await requireAuth();
    const userId = user.gscUserId;
    const tenantId = user.tenantId;
    if (!userId || !tenantId) {
      return NextResponse.json(
        { error: "Missing user identity" },
        { status: 400 }
      );
    }

    await opsApiFetch(
      `/api/v1/agents/me?userId=${userId}&tenantId=${tenantId}`,
      "DELETE"
    );

    return new NextResponse(null, { status: 204 });
  } catch {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
}
