/**
 * POST /api/integrations/disconnect
 * Disconnects an integration for the authenticated user
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedEmail } from "@/lib/utils/auth-helpers.util";
import { logger } from "@/lib/logger";
import prisma from "@/lib/db";
import { integrationsAdapter } from "@/lib/adapters/integrations";

export const dynamic = "force-dynamic";

const VALID_TYPES = [
  "google_calendar",
  "outlook_calendar",
  "salesforce",
  "hubspot",
  "zapier",
  "make",
  "whatsapp",
];

export async function POST(request: NextRequest) {
  try {
    const userEmail = await getAuthenticatedEmail(request, auth);

    if (!userEmail) {
      logger.warn("Unauthorized disconnect request");
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await request.json();
    const { type } = body;

    if (!type || !VALID_TYPES.includes(type)) {
      return NextResponse.json(
        { error: "Invalid integration type" },
        { status: 400 },
      );
    }

    // Get user from database
    const user = await prisma.users.findUnique({
      where: { email: userEmail },
      select: { id: true },
    });

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

    // Find and update the integration
    const integration = await integrationsAdapter.findUnique({
      where: {
        userId_type: {
          userId: user.id,
          type: type,
        },
      },
    });

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

    // Update integration to disconnected status and clear tokens
    await integrationsAdapter.update({
      where: { id: integration.id },
      data: {
        status: "disconnected",
        accessToken: null,
        refreshToken: null,
        config: {},
        lastError: null,
        updatedAt: new Date(),
      },
    });

    logger.info("Integration disconnected", { userEmail, type });

    return NextResponse.json({
      success: true,
      message: `${type} integration disconnected successfully`,
    });
  } catch (error) {
    logger.error("Disconnect integration error", {
      error: error instanceof Error ? error.message : "Unknown error",
    });

    return NextResponse.json(
      { error: "Failed to disconnect integration" },
      { status: 500 },
    );
  }
}
