import { User } from "@calchat/shared";
import { UserRepository, CreateUserData } from "../../services/interfaces";
import { Logged } from "../../logging";
import { UserModel, UserDocument } from "./models";

function toUser(doc: UserDocument): User {
  return {
    id: doc._id.toString(),
    email: doc.email,
    userName: doc.userName,
    passwordHash: doc.passwordHash,
    createdAt: doc.createdAt,
    updatedAt: doc.updatedAt,
  };
}

@Logged("MongoUserRepository")
export class MongoUserRepository implements UserRepository {
  async findById(id: string): Promise<User | null> {
    const user = await UserModel.findById(id);
    return user ? toUser(user) : null;
  }

  async findByEmail(email: string): Promise<User | null> {
    const user = await UserModel.findOne({ email: email.toLowerCase() });
    return user ? toUser(user) : null;
  }

  async findByUserName(userName: string): Promise<User | null> {
    const user = await UserModel.findOne({ userName });
    return user ? toUser(user) : null;
  }

  async create(data: CreateUserData): Promise<User> {
    const user = await UserModel.create(data);
    return toUser(user);
  }
}
