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

const AGENT_RUNNER_URL = process.env.AGENT_RUNNER_URL ?? "http://localhost:3333";

export async function POST(
  req: Request,
  { params }: { params: Promise<{ projectId: string; sessionId: string }> }
) {
  try {
    const { projectId, sessionId } = await params;

    // Authenticate via Workspace API key (desktop) OR browser session.
    // NOTE: this must match the create/get session routes — using browser-only
    // auth here caused the desktop's vibn_sk_ key to get a 401, which the
    // desktop treated as "session expired" and signed the user out (→ login page).
    const principal = await requireWorkspacePrincipal(req);
    if (principal instanceof NextResponse) return principal;

    const userRow = await queryOne<{ id: string; data: any }>(
      `SELECT id, data FROM fs_users WHERE id = $1 LIMIT 1`,
      [principal.userId]
    );
    const email = userRow?.data?.email;
    if (!email) {
      return NextResponse.json({ error: "User email not found" }, { status: 404 });
    }

    // Verify ownership
    const rows = await query<{ status: string }>(
      `SELECT s.status FROM agent_sessions s
       JOIN fs_projects p ON p.id::text = s.project_id::text
       JOIN fs_users u ON u.id = p.user_id
       WHERE s.id = $1::uuid AND s.project_id::text = $2 AND u.data->>'email' = $3 LIMIT 1`,
      [sessionId, projectId, email]
    );

    if (rows.length === 0) {
      return NextResponse.json({ error: "Session not found" }, { status: 404 });
    }

    if (rows[0].status !== "running" && rows[0].status !== "pending") {
      return NextResponse.json({ error: "Session is not running" }, { status: 400 });
    }

    // Tell the agent runner to stop (best-effort)
    fetch(`${AGENT_RUNNER_URL}/agent/stop`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ sessionId }),
    }).catch(() => {});

    // Mark as stopped in DB immediately
    await query(
      `UPDATE agent_sessions
       SET status = 'stopped', completed_at = now(), updated_at = now(),
           output = output || '[{"ts": "now", "type": "info", "text": "Stopped by user."}]'::jsonb
       WHERE id = $1::uuid`,
      [sessionId]
    );

    return NextResponse.json({ ok: true });
  } catch (err) {
    console.error("[agent/sessions/stop]", err);
    return NextResponse.json({ error: "Failed to stop session" }, { status: 500 });
  }
}
