import prisma from '../config/db.js';

const DEFAULT_ROLE_NAME = 'user';

// Idempotent: safe to call on every first-time sign-in without a separate seed step.
async function getDefaultRoleId(): Promise<number> {
  const role = await prisma.role.upsert({
    where: { name: DEFAULT_ROLE_NAME },
    update: {},
    create: { name: DEFAULT_ROLE_NAME, description: 'Default role for new sign-ups', isSystem: true },
  });
  return role.id;
}

export interface FirebaseProfile {
  firebaseUid: string;
  email: string;
  name: string;
  avatarUrl?: string | null;
  emailVerified?: boolean;
}

export function findUserByFirebaseUid(firebaseUid: string) {
  return prisma.user.findUnique({ where: { firebaseUid }, include: { role: true, organization: true } });
}

export function findUserByEmail(email: string) {
  return prisma.user.findUnique({ where: { email }, include: { role: true, organization: true } });
}

export function findUserById(id: number) {
  return prisma.user.findUnique({ where: { id }, include: { role: true, organization: true } });
}

export async function createFirebaseUser(profile: FirebaseProfile) {
  const roleId = await getDefaultRoleId();
  return prisma.user.create({
    data: {
      firebaseUid: profile.firebaseUid,
      email: profile.email,
      name: profile.name,
      avatarUrl: profile.avatarUrl ?? null,
      emailVerified: profile.emailVerified ?? false,
      lastLoginAt: new Date(),
      roleId,
    },
    include: { role: true, organization: true },
  });
}

/** Sets (or clears) the profile photo's S3 key; returns the key it replaced. */
export async function setAvatar(id: number, key: string | null) {
  const previous = (await prisma.user.findUnique({ where: { id } }))?.avatarUrl ?? null;
  await prisma.user.update({ where: { id }, data: { avatarUrl: key } });
  return previous;
}

export function updateProfile(id: number, data: { name: string; phone: string | null; jobTitle: string | null }) {
  return prisma.user.update({ where: { id }, data });
}

export function touchLastLogin(id: number) {
  return prisma.user.update({ where: { id }, data: { lastLoginAt: new Date() } });
}
