import { auth } from '@/auth';
import type { CurrentOrganizationContext, CurrentUserContext } from './types';
import { requireSession } from '@/lib/auth/session';

export async function getCurrentUser() {
  const session = await auth();

  return session?.user ?? null;
}

export async function requireCurrentUser() {
  const session = await requireSession();

  return session.user;
}

function getActiveOrganizationFromUser(
  user: NonNullable<Awaited<ReturnType<typeof getCurrentUser>>>
): CurrentOrganizationContext | null {
  if (!user.activeOrganizationId) {
    return null;
  }

  const organization = user.organizations.find((item) => item.id === user.activeOrganizationId);

  if (!organization) {
    return null;
  }

  return {
    id: organization.id,
    name: organization.name,
    slug: organization.slug,
    plan: organization.plan,
    imageUrl: organization.imageUrl
  };
}

export async function getCurrentUserContext(): Promise<CurrentUserContext | null> {
  const user = await getCurrentUser();

  if (!user) {
    return null;
  }

  const activeOrganization = getActiveOrganizationFromUser(user);
  const membership = activeOrganization
    ? {
        userId: user.id,
        organizationId: activeOrganization.id,
        role: user.activeMembershipRole ?? 'user',
        businessRole: user.activeBusinessRole ?? 'sales_support',
        permissions: user.activePermissions
      }
    : null;

  return {
    user,
    activeOrganization,
    membership,
    permissions: user.activePermissions,
    businessRole: user.activeBusinessRole ?? null
  };
}
