import { NextResponse } from "next/server";
import { DepartmentKey } from "@prisma/client";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { canAccessMarketing, canManageMarketing } from "@/lib/marketing/persistence";

type UpsertConnectionBody = {
  accountId?: string;
  pageId?: string;
  pageName?: string;
  pageAccessToken?: string;
  tokenExpiresAt?: string | null;
};

function mapConnection(connection: {
  id: string;
  accountId: string;
  pageId: string;
  pageName: string;
  isActive: boolean;
  lastSyncedAt: Date | null;
  tokenExpiresAt: Date | null;
}) {
  return {
    id: connection.id,
    accountId: connection.accountId,
    pageId: connection.pageId,
    pageName: connection.pageName,
    isActive: connection.isActive,
    lastSyncedAt: connection.lastSyncedAt ? connection.lastSyncedAt.toISOString() : null,
    tokenExpiresAt: connection.tokenExpiresAt ? connection.tokenExpiresAt.toISOString() : null,
  };
}

export async function GET() {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!canAccessMarketing(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const [connection, latestRun] = await Promise.all([
    prisma.marketingMetaConnection.findFirst({
      where: {
        department: DepartmentKey.marketing,
        isActive: true,
      },
      orderBy: { updatedAt: "desc" },
    }),
    prisma.marketingSyncRun.findFirst({
      where: { department: DepartmentKey.marketing },
      orderBy: { createdAt: "desc" },
    }),
  ]);

  return NextResponse.json({
    ok: true,
    connection: connection ? mapConnection(connection) : null,
    latestRun: latestRun
      ? {
          id: latestRun.id,
          status: latestRun.status,
          message: latestRun.message,
          rowsIngested: latestRun.rowsIngested,
          startedAt: latestRun.startedAt.toISOString(),
          completedAt: latestRun.completedAt ? latestRun.completedAt.toISOString() : null,
        }
      : null,
  });
}

export async function POST(request: Request) {
  const session = await getServerSession(authOptions);
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  if (!canManageMarketing(session.user.role, session.user.department)) {
    return NextResponse.json({ error: "Only owner/marketing leader can configure Meta connection." }, { status: 403 });
  }

  const body = (await request.json()) as UpsertConnectionBody;
  const accountId = body.accountId?.trim() ?? "";
  const pageId = body.pageId?.trim() ?? "";
  const pageName = body.pageName?.trim() ?? "";
  const pageAccessToken = body.pageAccessToken?.trim() ?? "";
  const tokenExpiresAt = body.tokenExpiresAt ? new Date(body.tokenExpiresAt) : null;

  if (!accountId || !pageId || !pageName || !pageAccessToken) {
    return NextResponse.json({ error: "accountId, pageId, pageName and pageAccessToken are required." }, { status: 400 });
  }

  const connection = await prisma.$transaction(async (tx) => {
    await tx.marketingMetaConnection.deleteMany({
      where: {
        department: DepartmentKey.marketing,
        isActive: false,
      },
    });

    await tx.marketingMetaConnection.updateMany({
      where: {
        department: DepartmentKey.marketing,
        isActive: true,
      },
      data: {
        isActive: false,
      },
    });

    return tx.marketingMetaConnection.create({
      data: {
        department: DepartmentKey.marketing,
        accountId,
        pageId,
        pageName,
        pageAccessToken,
        tokenExpiresAt: tokenExpiresAt && !Number.isNaN(tokenExpiresAt.getTime()) ? tokenExpiresAt : null,
        connectedById: session.user.id,
        isActive: true,
      },
    });
  });

  return NextResponse.json({ ok: true, connection: mapConnection(connection) });
}
