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() - 2 * 24 * 60 * 60 * 1000);

    // A done task clears 48h after completion. One that was already overdue
    // by the time it got marked done was late anyway, so it skips the grace
    // period entirely. And a done occurrence of a recurring task is dropped
    // right away as soon as a more recently completed occurrence of the same
    // series exists — only the latest completed run of a repeat should ever
    // show up as "done".
    const { rows: deleted } = teamId
      ? await sql<{ id: string }>`
          DELETE FROM tasks t
          WHERE t.status = 'done'
            AND t.completed_at IS NOT NULL
            AND (
              t.completed_at <= ${expiryThreshold}
              OR (t.deadline IS NOT NULL AND t.deadline < t.completed_at)
              OR EXISTS (
                SELECT 1 FROM tasks newer
                WHERE newer.id <> t.id
                  AND newer.status = 'done'
                  AND newer.completed_at IS NOT NULL
                  AND COALESCE(newer.source_task_id, newer.id) = COALESCE(t.source_task_id, t.id)
                  AND (
                    newer.completed_at > t.completed_at
                    OR (newer.completed_at = t.completed_at AND newer.id > t.id)
                  )
              )
            )
            AND t.team_id = ${teamId}
          RETURNING t.id
        `
      : await sql<{ id: string }>`
          DELETE FROM tasks t
          WHERE t.status = 'done'
            AND t.completed_at IS NOT NULL
            AND (
              t.completed_at <= ${expiryThreshold}
              OR (t.deadline IS NOT NULL AND t.deadline < t.completed_at)
              OR EXISTS (
                SELECT 1 FROM tasks newer
                WHERE newer.id <> t.id
                  AND newer.status = 'done'
                  AND newer.completed_at IS NOT NULL
                  AND COALESCE(newer.source_task_id, newer.id) = COALESCE(t.source_task_id, t.id)
                  AND (
                    newer.completed_at > t.completed_at
                    OR (newer.completed_at = t.completed_at AND newer.id > t.id)
                  )
              )
            )
            AND t.user_id = ${user.id}
            AND t.team_id IS NULL
          RETURNING t.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 });
  }
}
