/**
 * GET /api/client-portal/auth/verify?token=TOKEN
 * Validates the magic link token, sets a session, and
 * redirects to the client dashboard.
 */

import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { setClientSessionCookie, type ClientSession } from "@/lib/client-auth";
import { resolvePortalConfig } from "@/lib/portal-config";
import { resolvePermissions } from "@/lib/portal-permissions";

export const dynamic = "force-dynamic";

const APP_URL = process.env.NEXT_PUBLIC_APP_URL || "https://app.meseo.io";

export async function GET(req: Request) {
  const { searchParams } = new URL(req.url);
  const token = searchParams.get("token");

  if (!token) {
    return NextResponse.redirect(`${APP_URL}/client/login?error=missing_token`);
  }

  const user = await prisma.clientUser.findUnique({
    where: { accessToken: token },
    include: { portal: { include: { brand: { select: { id: true } } } } },
  });

  if (!user || !user.isActive || !user.portal.isEnabled) {
    return NextResponse.redirect(`${APP_URL}/client/login?error=invalid_token`);
  }

  if (user.tokenExpiresAt && user.tokenExpiresAt < new Date()) {
    return NextResponse.redirect(`${APP_URL}/client/login?error=token_expired`);
  }

  // Clear token (single-use) and update last login
  await prisma.clientUser.update({
    where: { id: user.id },
    data: { accessToken: null, tokenExpiresAt: null, lastLoginAt: new Date() },
  });

  const portalConfig = resolvePortalConfig(user.portal.portalConfig, user.portal.allowedPages);
  const session: ClientSession = {
    portalId: user.portalId,
    clientUserId: user.id,
    brandId: user.portal.brandId,
    email: user.email,
    role: user.role,
    permissions: resolvePermissions(user.role, user.permissions as Record<string, boolean> | null),
    agencyName: user.portal.agencyName,
    agencyLogo: user.portal.agencyLogo,
    primaryColor: user.portal.primaryColor,
    allowedPages: user.portal.allowedPages,
    portalConfig,
    hideSourceBranding: user.portal.hideSourceBranding,
  };

  setClientSessionCookie(session);

  return NextResponse.redirect(`${APP_URL}/client/${user.portal.brandId}/dashboard`);
}
