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 projects = sequelize.define(
    'projects',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      name: {
        type: DataTypes.TEXT,
      },
      description: {
        type: DataTypes.TEXT,
      },
      status: {
        type: DataTypes.ENUM,
        values: ['active', 'completed', 'archived'],
      },
      startDate: {
        type: DataTypes.DATE,
      },
      endDate: {
        type: DataTypes.DATE,
      },
      importHash: {
        type: DataTypes.STRING(255),
        allowNull: true,
        unique: true,
      },
    },
    {
      timestamps: true,
      paranoid: true,
      freezeTableName: true,
    },
  );

  projects.associate = (db) => {
    db.projects.belongsTo(db.users, {
      as: 'createdBy',
    });

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

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

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

    db.projects.belongsToMany(db.trials, {
      as: 'trials',
      foreignKey: 'projectId',
      otherKey: 'trialId',
      through: 'projects_trials',
      constraints: false,
    });
    
    // File attachment association (polymorphic usually handled in service, but we can define hasMany if we use a specific convention)
    // The `file` model uses `belongsTo` string.
    // So we don't strictly need an association here unless we want Sequelize to include it automatically.
    // But `file` model has `belongsTo` (string) and `belongsToId` (UUID).
    // So we can define:
    db.projects.hasMany(db.file, {
      as: 'documentation',
      foreignKey: 'belongsToId',
      constraints: false,
      scope: {
        belongsTo: 'projects',
        belongsToColumn: 'documentation', // User mentioned "supporting documentation". I'll use this as the 'column' differentiator if needed.
      },
    });
  };

  return projects;
};
