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

import { http } from "@/shared/api/httpClient";
import { API_ROUTES } from "@/shared/constants/api-routes";

interface GenerationStatusResponse {
  id: string;
  status: "queued" | "processing" | "done" | "error";
  result?: string | null;
  createdAt?: string;
  finishedAt?: string | null;
}

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    // This runs on the server and can access HttpOnly cookies
    const response = await http.get<GenerationStatusResponse>(
      API_ROUTES.statusGeneration(id),
      {
        cache: "no-store", // Don't cache status checks
      }
    );

    // Generate imageUrl if status is done
    let imageUrl: string | null = null;
    if (response.status === "done") {
      const apiUrl = process.env.NEXT_PUBLIC_API_URL || "";
      imageUrl = `${apiUrl}/partner-portrait/${id}/image`;
    }

    return NextResponse.json({
      id: response.id,
      status: response.status,
      imageUrl,
    });
  } catch {
    // Return error status without breaking
    return NextResponse.json(
      { error: "Failed to fetch status" },
      { status: 500 }
    );
  }
}
