import type { User } from '@/lib/auth';
import { resolveAvatarUrl } from '@/lib/avatar';
import { db } from '@/lib/prisma';
import type { UserProfile } from '@repo/api-contract';

export async function getUserProfile(user: User, complexId?: string): Promise<UserProfile> {
  const dbUser = await db.user.findUnique({
    where: { id: user.id },
    select: {
      id: true,
      name: true,
      email: true,
      image: true,
      createdAt: true,
    },
  });

  if (!dbUser) {
    throw new Error('User not found.');
  }

  let role = 'member';

  if (complexId) {
    const complexUser = await db.complexUser.findUnique({
      where: {
        complexId_userId: {
          complexId,
          userId: user.id,
        },
      },
    });

    if (complexUser) {
      role = complexUser.role.toLowerCase();
    }
  }

  return {
    id: dbUser.id,
    fullName: dbUser.name,
    email: dbUser.email,
    role,
    avatarUrl: resolveAvatarUrl({
      email: dbUser.email,
      image: dbUser.image,
    }),
    createdAt: dbUser.createdAt.toISOString(),
  };
}
