import { Client } from 'cozy-client'
import { IUserProfileManager, UserProfile } from './dataChallengeContracts'
import { USERPROFILE_DOCTYPE } from 'doctypes'

export default class UserProfileManager implements IUserProfileManager {
  private readonly _client: Client

  //private readonly _queryRunner: QueryRunner

  constructor(_client: Client) {
    this._client = _client
    //this._queryRunner = new QueryRunner(this._client)
  }

  public async getUserProfile(): Promise<UserProfile | null> {
    const { data: userProfiles } = await this._client.query(
      this._client.find(USERPROFILE_DOCTYPE).limitBy(1)
    )

    return userProfiles[0] ? userProfiles[0] : null
  }

  public async updateUserProfile(attributes: {
    [key: string]: string | boolean
  }): Promise<UserProfile | null> {
    const { data: userProfile } = await this._client
      .query(this._client.find(USERPROFILE_DOCTYPE).limitBy(1))
      .then(async ({ data }: any) => {
        const doc = data[0]
        return await this._client.save({
          ...doc,
          ...attributes,
        })
      })
    return userProfile ? userProfile : null
  }
}