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 ai_runs = sequelize.define(
    'ai_runs',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },

run_type: {
        type: DataTypes.ENUM,
      
      

        values: [

"expand_map",


"explain_links",


"suggest_missing_nodes",


"summarize_sources",


"generate_business_plan",


"generate_exec_summary",


"generate_pitch_deck_outline",


"deal_structure_advice",


"risk_review",


"financial_model_outline"

        ],

      },

status: {
        type: DataTypes.ENUM,
      
      

        values: [

"queued",


"running",


"succeeded",


"failed",


"canceled"

        ],

      },

prompt: {
        type: DataTypes.TEXT,
      
      

      },

result_text: {
        type: DataTypes.TEXT,
      
      

      },

cost_usd: {
        type: DataTypes.DECIMAL,
      
      

      },

tokens_in: {
        type: DataTypes.INTEGER,
      
      

      },

tokens_out: {
        type: DataTypes.INTEGER,
      
      

      },

started_at: {
        type: DataTypes.DATE,
      
      

      },

finished_at: {
        type: DataTypes.DATE,
      
      

      },

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

  ai_runs.associate = (db) => {


/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity















    db.ai_runs.hasMany(db.business_plan_versions, {
      as: 'business_plan_versions_generated_by_run',
      foreignKey: {
          name: 'generated_by_runId',
      },
      constraints: false,
    });


    db.ai_runs.hasMany(db.pitch_decks, {
      as: 'pitch_decks_generated_by_run',
      foreignKey: {
          name: 'generated_by_runId',
      },
      constraints: false,
    });






//end loop



    db.ai_runs.belongsTo(db.projects, {
      as: 'project',
      foreignKey: {
        name: 'projectId',
      },
      constraints: false,
    });

    db.ai_runs.belongsTo(db.organizations, {
      as: 'organizations',
      foreignKey: {
        name: 'organizationsId',
      },
      constraints: false,
    });



    db.ai_runs.hasMany(db.file, {
      as: 'result_files',
      foreignKey: 'belongsToId',
      constraints: false,
      scope: {
        belongsTo: db.ai_runs.getTableName(),
        belongsToColumn: 'result_files',
      },
    });


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

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



  return ai_runs;
};


