import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { Device, DeviceDocument } from './schemas/device.schema';

@Injectable()
export class DevicesRepository {
  constructor(@InjectModel(Device.name) private readonly deviceModel: Model<DeviceDocument>) {}

  async upsert(userId: string, payload: Omit<Partial<Device>, 'userId'>): Promise<DeviceDocument> {
    const filter = payload.deviceId
      ? { userId: new Types.ObjectId(userId), deviceId: payload.deviceId }
      : { userId: new Types.ObjectId(userId), fcmToken: payload.fcmToken };

    return this.deviceModel
      .findOneAndUpdate(
        filter,
        {
          $set: {
            ...payload,
            userId: new Types.ObjectId(userId),
            isActive: true,
            lastSeenAt: new Date(),
          },
        },
        { new: true, upsert: true, setDefaultsOnInsert: true },
      )
      .exec();
  }

  async deactivate(userId: string, payload: { fcmToken?: string; deviceId?: string }): Promise<DeviceDocument | null> {
    const filter: Record<string, unknown> = { userId: new Types.ObjectId(userId) };
    if (payload.deviceId) {
      filter.deviceId = payload.deviceId;
    } else if (payload.fcmToken) {
      filter.fcmToken = payload.fcmToken;
    } else {
      return null;
    }

    return this.deviceModel
      .findOneAndUpdate(filter, { isActive: false, lastSeenAt: new Date() }, { new: true })
      .exec();
  }
}
