import { NextRequest, NextResponse } from "next/server";

import { ensureChatUserExists, mintChatUserToken } from "@/app/lib/agoraChatServer";

// Mints an Agora Chat user token for image/voice attachments inside a
// consultation. Chat usernames are scoped to the consultation itself
// (`cs-<id>-user` / `cs-<id>-astro`), not to the caller's real account
// id — the astrologer's own session has no reliable numeric customer
// id anywhere in its API responses (confirmed while building this;
// `GET /astrologer/consultation/active` never carries one), so a
// per-consultation identity is both simpler and the only thing both
// sides can independently derive.
//
// Authorization here isn't "is this token valid" alone — a valid
// token could belong to a different customer/astrologer entirely.
// Ownership of *this* consultation is confirmed by checking that the
// caller's own currently-active consultation (per the Go backend,
// never trusted from the client) matches the id being requested.

const USER_ACTIVE_URL = "https://api.astrology.togwe.com/api/user/consultation/active";
const ASTROLOGER_ACTIVE_URL = "https://api.astrology.togwe.com/api/astrologer/consultation/active";

export async function POST(request: NextRequest) {
  try {
    const authorization = request.headers.get("authorization");

    if (!authorization) {
      return NextResponse.json(
        { success: false, message: "Authentication token is required." },
        { status: 401 }
      );
    }

    const body = await request.json();
    const audience = body?.audience === "astrologer" ? "astrologer" : "user";
    const consultationId = Number(body?.consultationId);

    if (!consultationId) {
      return NextResponse.json(
        { success: false, message: "consultationId is required." },
        { status: 400 }
      );
    }

    const activeUrl = audience === "astrologer" ? ASTROLOGER_ACTIVE_URL : USER_ACTIVE_URL;

    const activeResponse = await fetch(activeUrl, {
      method: "GET",
      headers: { Accept: "application/json", Authorization: authorization },
      cache: "no-store",
    });

    const activeData = await activeResponse.json();

    // Both audiences' /active responses use this field name
    // (confirmed live for both — see CLAUDE.md's Chat/Call
    // consultations section for the captured astrologer-side shape).
    const ownedConsultationId = Number(activeData?.data?.consultation_id) || 0;

    if (!activeResponse.ok || !ownedConsultationId || ownedConsultationId !== consultationId) {
      return NextResponse.json(
        { success: false, message: "This consultation isn't currently active for you." },
        { status: 403 }
      );
    }

    const role = audience === "astrologer" ? "astro" : "user";
    const peerRole = audience === "astrologer" ? "user" : "astro";

    const username = `cs-${consultationId}-${role}`;
    const peerUsername = `cs-${consultationId}-${peerRole}`;

    await ensureChatUserExists(username);

    const token = mintChatUserToken(username);

    return NextResponse.json({
      success: true,
      appId: process.env.NEXT_PUBLIC_AGORA_APP_ID,
      username,
      peerUsername,
      token,
    });
  } catch (error) {
    console.error("Agora chat-token error:", error);

    return NextResponse.json(
      { success: false, message: "Unable to mint a chat token." },
      { status: 500 }
    );
  }
}
