import type mongoose from 'mongoose';
import { UserModel } from '../../schemas/user.schema.js';
import type { CreateUserInput, UpdateUserInput } from '@meshitrack/shared';

export class UsersRepository {
  public async findByKeycloakId(keycloakId: string, session?: mongoose.ClientSession) {
    return UserModel.findOne({ keycloakId }, null, { session }).lean().exec();
  }

  public async findById(id: string) {
    return UserModel.findById(id).lean().exec();
  }

  public async create(data: CreateUserInput) {
    const user = new UserModel(data);
    const saved = await user.save();
    return saved.toObject();
  }

  public async update(keycloakId: string, data: UpdateUserInput, session?: mongoose.ClientSession) {
    return UserModel.findOneAndUpdate(
      { keycloakId },
      { $set: data },
      { new: true, lean: true, session },
    ).exec();
  }

  public async upsertFromToken(keycloakId: string, email: string, displayName: string) {
    return UserModel.findOneAndUpdate(
      { keycloakId },
      {
        $set: { email, displayName },
        $setOnInsert: { keycloakId, householdIds: [], defaultHouseholdId: null },
      },
      { upsert: true, new: true, lean: true },
    ).exec();
  }
}
