import { logApiError } from "@/lib/api/security";
import { NextResponse } from "next/server";
import { canAccessWorkspace } from "@/lib/developers/auth";
import { sql } from "@/lib/db/postgres";
import { createRouteClient } from "@/lib/supabase/route";

export async function POST(req: Request) {
  try {
    const supabase = await createRouteClient();
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const body = await req.json().catch(() => ({}));
    const teamId = typeof body.teamId === "string" && body.teamId ? body.teamId : null;

    const accessible = await canAccessWorkspace(user.id, teamId);
    if (!accessible) return NextResponse.json({ error: "Forbidden" }, { status: 403 });

    const expiryThreshold = new Date(Date.now() - 24 * 60 * 60 * 1000);

    const { rows: deleted } = teamId
      ? await sql<{ id: string }>`
          DELETE FROM tasks
          WHERE status = 'done'
            AND completed_at IS NOT NULL
            AND completed_at <= ${expiryThreshold}
            AND team_id = ${teamId}
          RETURNING id
        `
      : await sql<{ id: string }>`
          DELETE FROM tasks
          WHERE status = 'done'
            AND completed_at IS NOT NULL
            AND completed_at <= ${expiryThreshold}
            AND user_id = ${user.id}
            AND team_id IS NULL
          RETURNING id
        `;

    return NextResponse.json({ deletedCount: deleted.length });
  } catch (error) {
    logApiError("Task cleanup POST error", error);
    return NextResponse.json({ error: "Failed to clean up completed tasks" }, { status: 500 });
  }
}
