import "server-only";

import { redirect } from "next/navigation";
import { OrganizationDocumentType, UserRole } from "@prisma/client";
import { prisma } from "@/lib/prisma";
import { getSessionPayload } from "@/lib/auth/session";

type UserRecord = {
  id: string;
  email: string;
  name: string | null;
  role: UserRole;
  emailVerifiedAt: Date | null;
};

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

  if (!session) {
    return null;
  }

  try {
    return await prisma.user.findUnique({
      where: { id: session.userId },
      select: {
        id: true,
        email: true,
        name: true,
        role: true,
        emailVerifiedAt: true,
      },
    });
  } catch {
    return null;
  }
}

export async function requireUser() {
  const user = await getCurrentUser();

  if (!user) {
    redirect("/login?error=auth_required");
  }

  return user as UserRecord;
}

export async function hasOrganization(userId: string) {
  const organization = await prisma.organization.findUnique({
    where: { userId },
    select: { id: true },
  });

  return Boolean(organization);
}

export async function hasCompletedOnboarding(userId: string) {
  try {
    const organization = await prisma.organization.findUnique({
      where: { userId },
      select: {
        onboardingCompletedAt: true,
        documents: {
          where: {
            type: OrganizationDocumentType.ACTA_CONSTITUTIVA,
          },
          select: {
            id: true,
          },
          take: 1,
        },
      },
    });

    if (!organization?.onboardingCompletedAt) {
      return false;
    }

    return organization.documents.length > 0;
  } catch {
    // Backward compatibility while migration is pending in some environments.
    const legacyOrganization = await prisma.organization.findUnique({
      where: { userId },
      select: { id: true },
    });

    return Boolean(legacyOrganization);
  }
}

export async function requireOnboardedUser() {
  const user = await requireUser();
  const onboarded = await hasCompletedOnboarding(user.id);

  if (!onboarded) {
    redirect("/onboarding");
  }

  return user;
}
