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("integration_connections")
      .select("id, team_id, provider, config")
      .eq("id", id)
      .eq("provider", "google_calendar")
      .maybeSingle();

    if (!existing) {
      return NextResponse.json({ error: "Google Calendar connection 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 nextConfig = {
      ...(existing.config || {}),
      ...(typeof body.calendarId === "string" || body.calendarId === null
        ? { calendarId: body.calendarId || null }
        : {}),
      ...(typeof body.calendarSummary === "string" || body.calendarSummary === null
        ? { calendarSummary: body.calendarSummary || null }
        : {}),
    };

    const { data, error } = await supabase
      .from("integration_connections")
      .update({
        ...(typeof body.name === "string" ? { name: body.name.trim() || "Google Calendar" } : {}),
        ...(typeof body.isActive === "boolean" ? { is_active: body.isActive } : {}),
        config: nextConfig,
      })
      .eq("id", id)
      .select(
        "id, user_id, team_id, provider, name, config, event_types, is_active, last_delivery_at, last_response_status, last_error, created_at, updated_at"
      )
      .single();

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

    return NextResponse.json({ connection: data });
  } catch (error) {
    logApiError("Google Calendar PATCH error:", error);
    return NextResponse.json(
      { error: "Failed to update Google Calendar connection" },
      { 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("integration_connections")
      .select("id, team_id, provider")
      .eq("id", id)
      .eq("provider", "google_calendar")
      .maybeSingle();

    if (!existing) {
      return NextResponse.json({ error: "Google Calendar connection 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("integration_connections").delete().eq("id", id);
    if (error) {
      return NextResponse.json({ error: error.message }, { status: 400 });
    }

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