import type mongoose from 'mongoose';
import { HouseholdModel } from '../../schemas/household.schema.js';
import type { CreateHouseholdInput, UpdateHouseholdInput } from '@meshitrack/shared';
import { HouseholdRole } from '@meshitrack/shared';

export class HouseholdsRepository {
  public async findById(id: string) {
    return HouseholdModel.findById(id).lean().exec();
  }

  public async findByInviteCode(inviteCode: string) {
    return HouseholdModel.findOne({ inviteCode }).lean().exec();
  }

  public async create(
    data: CreateHouseholdInput,
    ownerUserId: string,
    inviteCode: string,
    session?: mongoose.ClientSession,
  ) {
    const household = new HouseholdModel({
      ...data,
      ownerUserId,
      inviteCode,
      members: [{ userId: ownerUserId, role: HouseholdRole.OWNER, joinedAt: new Date() }],
    });
    const saved = await household.save({ session });
    return saved.toObject();
  }

  public async update(id: string, data: UpdateHouseholdInput) {
    return HouseholdModel.findByIdAndUpdate(id, { $set: data }, { new: true, lean: true }).exec();
  }

  public async addMember(
    id: string,
    userId: string,
    role: HouseholdRole,
    session?: mongoose.ClientSession,
  ) {
    return HouseholdModel.findByIdAndUpdate(
      id,
      { $push: { members: { userId, role, joinedAt: new Date() } } },
      { new: true, lean: true, session },
    ).exec();
  }

  public async updateInviteCode(id: string, inviteCode: string) {
    return HouseholdModel.findByIdAndUpdate(
      id,
      { $set: { inviteCode } },
      { new: true, lean: true },
    ).exec();
  }
}
