const BaseCrud = require("./baseCrud");

class ClientsService extends BaseCrud {
  constructor(logger, sequelize) {
    super(sequelize.models.Client);

    this.logger = logger;
    this.sequelize = sequelize;

    const { StaffMember, ClientInterest } = this.sequelize.models;

    this.ClientInclusion = [
      {
        model: StaffMember,
        as: "expert",
      },
    ];
    this.ClientInclusionExtended = [
      {
        model: StaffMember,
        as: "expert",
      },
      {
        model: ClientInterest,
        as: "interests",
      },
    ];
  }

  async save(changes) {
    return super.save(changes);
  }

  async update(id, changes) {
    return super.update(id, changes);
  }

  async saveInterest(clientId, interest) {
    this.logger.info({ data: { interest } }, "Saving interest for client.");

    let client = await this.getById(clientId);

    if (!client) throw Error("This client does not exists");

    interest.clientId = clientId;

    const { ClientInterest } = this.sequelize.models;

    // force new interest removing current id (history)
    delete interest.id;

    return ClientInterest.create(interest);
  }

  async updateInterest(interest) {
    this.logger.info({ data: { interest } }, "Saving interest for client.");
    return interest.save();
  }

  async getById(id) {
    return super.getById(id, this.ClientInclusion);
  }

  async getByEmail(email) {
    this.logger.info({ data: { email } }, "Retrieving a client by email");

    const { Client } = this.sequelize.models;

    return Client.findOne({
      where: { email },
      include: this.ClientInclusion,
    });
  }

  async getList(filters = {}) {
    return super.getList(filters, this.ClientInclusion);
  }
}

module.exports = ClientsService;
