import { logApiError } from "@/lib/api/security";
import { NextResponse } from "next/server";
import { canManageWorkspace } from "@/lib/developers/auth";
import {
  parseGoogleCalendarConfig,
  syncAllWorkspaceEventsToGoogleCalendar,
} from "@/lib/integrations/google-calendar";
import { createAdminClient } from "@/lib/supabase/admin";
import { createRouteClient } from "@/lib/supabase/route";
import type { IntegrationConnection } from "@/types";

export async function POST(
  _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 admin = createAdminClient();
    const { data: connection } = await admin
      .from("integration_connections")
      .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, secret_encrypted"
      )
      .eq("id", id)
      .eq("provider", "google_calendar")
      .maybeSingle();

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

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

    const config = parseGoogleCalendarConfig(connection.config);
    if (!config.calendarId) {
      return NextResponse.json(
        { error: "Pick a Google calendar before syncing" },
        { status: 400 }
      );
    }

    const result = await syncAllWorkspaceEventsToGoogleCalendar(
      admin,
      connection as IntegrationConnection & { secret_encrypted: string }
    );

    return NextResponse.json({
      synced: result.synced,
      calendarId: config.calendarId,
      calendarSummary: config.calendarSummary,
    });
  } catch (error) {
    logApiError("Google Calendar sync POST error:", error);
    return NextResponse.json(
      { error: "Failed to sync Google Calendar" },
      { status: 500 }
    );
  }
}
