/**
 * GET    /api/workspaces/[slug]/auth/[uuid]  — provider details
 * DELETE /api/workspaces/[slug]/auth/[uuid]?confirm=<name>
 *        Volumes KEPT by default (don't blow away user accounts).
 */

import { NextResponse } from 'next/server';
import { requireWorkspacePrincipal } from '@/lib/auth/workspace-auth';
import {
  getServiceInProject,
  deleteService,
  projectUuidOf,
  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 {
    const svc = await getServiceInProject(uuid, ws.coolify_project_uuid);
    return NextResponse.json({
      uuid: svc.uuid,
      name: svc.name,
      status: svc.status ?? null,
      projectUuid: projectUuidOf(svc),
    });
  } catch (err) {
    if (err instanceof TenantError) return NextResponse.json({ error: err.message }, { status: 403 });
    return NextResponse.json({ error: 'Provider not found' }, { status: 404 });
  }
}

export async function DELETE(
  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 });
  }

  let svc;
  try {
    svc = await getServiceInProject(uuid, ws.coolify_project_uuid);
  } catch (err) {
    if (err instanceof TenantError) return NextResponse.json({ error: err.message }, { status: 403 });
    return NextResponse.json({ error: 'Provider not found' }, { status: 404 });
  }

  const url = new URL(request.url);
  const confirm = url.searchParams.get('confirm');
  if (confirm !== svc.name) {
    return NextResponse.json(
      { error: 'Confirmation required', hint: `Pass ?confirm=${svc.name}` },
      { status: 409 }
    );
  }

  const deleteVolumes = url.searchParams.get('delete_volumes') === 'true';

  try {
    await deleteService(uuid, {
      deleteConfigurations: true,
      deleteVolumes,
      deleteConnectedNetworks: true,
      dockerCleanup: true,
    });
    return NextResponse.json({
      ok: true,
      deleted: { uuid, name: svc.name, volumesKept: !deleteVolumes },
    });
  } catch (err) {
    return NextResponse.json(
      { error: 'Coolify delete failed', details: err instanceof Error ? err.message : String(err) },
      { status: 502 }
    );
  }
}
