import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import {
  requireApiAuthWithOrg,
  requireApiAuthWithPermission,
  handleApiError,
} from "@/lib/api-auth";

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await requireApiAuthWithOrg();

    const { id } = await params;
    const integration = await prisma.integration.findFirst({
      where: { id, organizationId: session.user.orgId },
    });

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

    return NextResponse.json({ integration });
  } catch (error) {
    return handleApiError(error);
  }
}

export async function PUT(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await requireApiAuthWithPermission("integrations.manage");

    const { id } = await params;
    const existing = await prisma.integration.findFirst({
      where: { id, organizationId: session.user.orgId },
    });
    if (!existing) {
      return NextResponse.json(
        { error: "Integration not found" },
        { status: 404 }
      );
    }

    const body = await req.json();
    const { config, fieldMapping, enabled, triggerEvents, name, syncDirection } =
      body;

    const integration = await prisma.integration.update({
      where: { id },
      data: {
        ...(config !== undefined && { config }),
        ...(fieldMapping !== undefined && { fieldMapping }),
        ...(enabled !== undefined && { enabled }),
        ...(triggerEvents !== undefined && { triggerEvents }),
        ...(name !== undefined && { name }),
        ...(syncDirection !== undefined && { syncDirection }),
      },
    });

    return NextResponse.json({ integration });
  } catch (error) {
    return handleApiError(error);
  }
}

export async function DELETE(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await requireApiAuthWithPermission("integrations.manage");

    const { id } = await params;
    const existing = await prisma.integration.findFirst({
      where: { id, organizationId: session.user.orgId },
    });
    if (!existing) {
      return NextResponse.json(
        { error: "Integration not found" },
        { status: 404 }
      );
    }

    await prisma.integration.delete({ where: { id } });

    return NextResponse.json({ success: true });
  } catch (error) {
    return handleApiError(error);
  }
}
