import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';

import { authOptions } from '@/lib/auth';

type JsonRecord = Record<string, unknown>;
type SessionClaims = {
  roles?: string[];
  clientId?: string;
  tenantId?: string;
  subscriptionId?: string;
} | null;

function actorFromSession(session: SessionClaims): string {
  const roles = Array.isArray(session?.roles) ? session.roles : [];
  if (roles.includes('partner')) return 'partner';
  if (roles.includes('tenant-admin') || roles.includes('TENANT_ADMIN')) return 'invited_client_admin';
  if (roles.includes('admin') || roles.includes('ADMIN')) return 'internal_operator';
  return 'invited_tenant_user';
}

export async function GET() {
  const session = (await getServerSession(authOptions)) as SessionClaims;
  if (!session) {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  return NextResponse.json({
    status: 'ready',
    actor: actorFromSession(session),
    workspace: {
      clientId: session.clientId || null,
      tenantId: session.tenantId || null,
      subscriptionId: session.subscriptionId || null,
    },
  });
}

export async function POST(request: Request) {
  const session = (await getServerSession(authOptions)) as SessionClaims;
  if (!session) {
    return NextResponse.json({ message: 'Unauthorized' }, { status: 401 });
  }

  const body = (await request.json().catch(() => ({}))) as JsonRecord;
  const profile = typeof body.profile === 'object' && body.profile ? (body.profile as JsonRecord) : {};
  const preferences =
    typeof body.preferences === 'object' && body.preferences ? (body.preferences as JsonRecord) : {};

  const response = NextResponse.json({
    status: 'accepted',
    actor: actorFromSession(session),
    nextUrl: '/dashboard',
    workspace: {
      clientId: session.clientId || null,
      tenantId: session.tenantId || null,
      subscriptionId: session.subscriptionId || null,
    },
    profile,
    preferences,
  });

  response.cookies.set('portal_onboarding_complete', '1', {
    httpOnly: true,
    sameSite: 'lax',
    secure: process.env.NODE_ENV === 'production',
    path: '/',
    maxAge: 60 * 60 * 24 * 365,
  });

  response.cookies.set('portal_onboarding_actor', actorFromSession(session), {
    httpOnly: true,
    sameSite: 'lax',
    secure: process.env.NODE_ENV === 'production',
    path: '/',
    maxAge: 60 * 60 * 24 * 365,
  });

  return response;
}
