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

export async function DELETE(
  _req: Request,
  context: { params: Promise<{ id: string; linkId: string }> }
) {
  try {
    const supabase = await createRouteClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();

    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id, linkId } = await context.params;
    const { data: task } = await supabase
      .from("tasks")
      .select("id, user_id, team_id")
      .eq("id", id)
      .maybeSingle();

    if (!task) {
      return NextResponse.json({ error: "Task not found" }, { status: 404 });
    }

    const hasAccess =
      task.user_id === user.id &&
      !task.team_id
        ? true
        : await canAccessWorkspace(user.id, task.team_id || null);

    if (!hasAccess) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    const { error } = await supabase
      .from("github_issue_links")
      .delete()
      .eq("id", linkId)
      .eq("task_id", id);

    if (error) {
      return NextResponse.json({ error: error.message }, { status: 400 });
    }

    return NextResponse.json({ success: true });
  } catch (error) {
    logApiError("Task GitHub links DELETE error:", error);
    return NextResponse.json({ error: "Failed to delete GitHub link" }, { status: 500 });
  }
}
