import { initDb } from "@/lib/db";
import bcrypt from "bcryptjs";
import type { UserRole } from "@/types";
import type { User } from "@/lib/db/models/user";

/** Find an active user by email for credential authentication. */
export async function findUserByEmail(email: string) {
  const { User: UserModel } = initDb();
  return UserModel.findOne({
    where: { email: email.toLowerCase(), isActive: true },
  });
}

/** Verify a plaintext password against a bcrypt hash. */
export async function verifyPassword(
  plaintext: string,
  hash: string
): Promise<boolean> {
  return bcrypt.compare(plaintext, hash);
}

/** Hash a plaintext password for storage. */
export async function hashPassword(plaintext: string): Promise<string> {
  return bcrypt.hash(plaintext, 12);
}

/** Build session-safe user payload — never includes passwordHash. */
export function toSessionUser(user: User) {
  return {
    id: user.id,
    name: user.name,
    email: user.email,
    role: user.role as UserRole,
    workspaceId: user.workspaceId,
    image: user.avatarUrl,
  };
}
