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

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

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

    const { id } = await context.params;
    const { data: existing } = await supabase
      .from("calendar_feed_tokens")
      .select("id, team_id")
      .eq("id", id)
      .maybeSingle();

    if (!existing) {
      return NextResponse.json({ error: "Calendar feed not found" }, { status: 404 });
    }

    const manageable = await canManageWorkspace(user.id, existing.team_id || null);
    if (!manageable) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    const body = await req.json();
    const updates = {
      ...(typeof body.name === "string" ? { name: body.name.trim() || "Workspace calendar" } : {}),
      ...(typeof body.isActive === "boolean" ? { is_active: body.isActive } : {}),
    };

    const { data, error } = await supabase
      .from("calendar_feed_tokens")
      .update(updates)
      .eq("id", id)
      .select(
        "id, user_id, team_id, name, token_prefix, is_active, last_accessed_at, created_at, updated_at"
      )
      .single();

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

    return NextResponse.json({ feed: data });
  } catch (error) {
    logApiError("Calendar feeds PATCH error:", error);
    return NextResponse.json({ error: "Failed to update calendar feed" }, { status: 500 });
  }
}

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

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

    const { id } = await context.params;
    const { data: existing } = await supabase
      .from("calendar_feed_tokens")
      .select("id, team_id")
      .eq("id", id)
      .maybeSingle();

    if (!existing) {
      return NextResponse.json({ error: "Calendar feed not found" }, { status: 404 });
    }

    const manageable = await canManageWorkspace(user.id, existing.team_id || null);
    if (!manageable) {
      return NextResponse.json({ error: "Forbidden" }, { status: 403 });
    }

    const { error } = await supabase.from("calendar_feed_tokens").delete().eq("id", id);
    if (error) {
      return NextResponse.json({ error: error.message }, { status: 400 });
    }

    return NextResponse.json({ success: true });
  } catch (error) {
    logApiError("Calendar feeds DELETE error:", error);
    return NextResponse.json({ error: "Failed to delete calendar feed" }, { status: 500 });
  }
}
