/**
 * GET /api/workspaces/[slug]/apps/[uuid]/deployments
 *
 * Recent deployments for an app. Tenant-checked.
 */

import { NextResponse } from 'next/server';
import { requireWorkspacePrincipal } from '@/lib/auth/workspace-auth';
import {
  getApplicationInProject,
  listApplicationDeployments,
  TenantError,
} from '@/lib/coolify';

export async function GET(
  request: Request,
  { params }: { params: Promise<{ slug: string; uuid: string }> }
) {
  const { slug, uuid } = await params;
  const principal = await requireWorkspacePrincipal(request, { targetSlug: slug });
  if (principal instanceof NextResponse) return principal;

  const ws = principal.workspace;
  if (!ws.coolify_project_uuid) {
    return NextResponse.json({ error: 'Workspace has no Coolify project yet' }, { status: 503 });
  }

  try {
    await getApplicationInProject(uuid, ws.coolify_project_uuid);
    const deployments = await listApplicationDeployments(uuid);
    return NextResponse.json({ deployments });
  } catch (err) {
    if (err instanceof TenantError) {
      return NextResponse.json({ error: err.message }, { status: 403 });
    }
    return NextResponse.json(
      { error: 'Coolify request failed', details: String(err) },
      { status: 502 }
    );
  }
}
