/**
 * GET /api/workspaces/[slug] — workspace details
 */

import { NextResponse } from "next/server";
import { requireWorkspacePrincipal } from "@/lib/auth/workspace-auth";
import { queryOne } from "@/lib/db-postgres";

export const dynamic = "force-dynamic";

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

  const w = principal.workspace;

  // Fetch the onboarding metadata from the owner's fs_users row
  const ownerRow = await queryOne<{ data: any }>(
    `SELECT data FROM fs_users WHERE id = $1 LIMIT 1`,
    [w.owner_user_id],
  );
  const isAgency = !!ownerRow?.data?.onboarding?.isAgency;

  return NextResponse.json({
    id: w.id,
    slug: w.slug,
    name: w.name,
    coolifyProjectUuid: w.coolify_project_uuid,
    coolifyTeamId: w.coolify_team_id,
    giteaOrg: w.gitea_org,
    giteaBotUsername: w.gitea_bot_username,
    giteaBotReady: !!(w.gitea_bot_username && w.gitea_bot_token_encrypted),
    provisionStatus: w.provision_status,
    provisionError: w.provision_error,
    createdAt: w.created_at,
    updatedAt: w.updated_at,
    isAgency,
    principal: {
      source: principal.source,
      apiKeyId: principal.apiKeyId ?? null,
    },
  });
}
