const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');

module.exports = function (sequelize, DataTypes) {
  const clients = sequelize.define(
    'clients',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },

      first_name: {
        type: DataTypes.TEXT,
      },

      last_name: {
        type: DataTypes.TEXT,
      },

      birth_date: {
        type: DataTypes.DATE,
      },

      phone: {
        type: DataTypes.TEXT,
      },

      address: {
        type: DataTypes.TEXT,
      },

      id_type: {
        type: DataTypes.ENUM,

        values: ['CIN', 'Passeport'],
      },

      id_number: {
        type: DataTypes.TEXT,
      },

      id_issue_date: {
        type: DataTypes.DATE,
      },

      license_number: {
        type: DataTypes.TEXT,
      },

      license_issue_date: {
        type: DataTypes.DATE,
      },

      id_copy_url: {
        type: DataTypes.TEXT,
      },

      license_copy_url: {
        type: DataTypes.TEXT,
      },

      importHash: {
        type: DataTypes.STRING(255),
        allowNull: true,
        unique: true,
      },
    },
    {
      timestamps: true,
      paranoid: true,
      freezeTableName: true,
    },
  );

  clients.associate = (db) => {
    /// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity

    db.clients.hasMany(db.claims, {
      as: 'claims_client',
      foreignKey: {
        name: 'clientId',
      },
      constraints: false,
    });

    db.clients.hasMany(db.reservations, {
      as: 'reservations_client',
      foreignKey: {
        name: 'clientId',
      },
      constraints: false,
    });

    //end loop

    db.clients.belongsTo(db.tenants, {
      as: 'tenant',
      foreignKey: {
        name: 'tenantId',
      },
      constraints: false,
    });

    db.clients.belongsTo(db.agences, {
      as: 'agences',
      foreignKey: {
        name: 'agencesId',
      },
      constraints: false,
    });

    db.clients.belongsTo(db.users, {
      as: 'createdBy',
    });

    db.clients.belongsTo(db.users, {
      as: 'updatedBy',
    });
  };

  return clients;
};
