import { DataTypes } from 'sequelize';
import sequelize from '../config/database.js';

/**
 * ConfigSetting Model
 * Stores configuration key-value pairs at varying scopes (SYSTEM, PROJECT, USER).
 * Secrets are encrypted at the application layer before storage.
 */
const ConfigSetting = sequelize.define('ConfigSetting', {
  id: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    primaryKey: true
  },
  scope: {
    type: DataTypes.ENUM('SYSTEM', 'PROJECT', 'USER'),
    allowNull: false,
    comment: 'The hierarchy level of this setting'
  },
  scopeId: {
    type: DataTypes.UUID,
    allowNull: true,
    field: 'scope_id',
    comment: 'NULL for SYSTEM, ProjectID for PROJECT, UserId for USER'
  },
  key: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      notEmpty: true
    }
  },
  value: {
    type: DataTypes.JSONB,
    allowNull: false,
    comment: 'Stores the actual config value. Encrypted string if isSecret=true'
  },
  isSecret: {
    type: DataTypes.BOOLEAN,
    defaultValue: false,
    field: 'is_secret',
    comment: 'If true, value is encrypted using AES-256-GCM'
  },
  schemaVersion: {
    type: DataTypes.INTEGER,
    defaultValue: 1,
    field: 'schema_version',
    comment: 'Used for future schema migrations of the config value itself'
  },
  createdAt: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW,
    field: 'created_at'
  },
  updatedAt: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW,
    field: 'updated_at'
  }
}, {
  tableName: 'config_settings',
  timestamps: true,
  indexes: [
    {
      // Ensure unique key per scope/scopeId combination
      unique: true,
      fields: ['scope', 'scope_id', 'key'],
      // Note: In Postgres, multiple NULLs (for scope_id) are distinct by default in unique constraints
      // We will handle specific SYSTEM scope uniqueness validation in the Service layer or
      // rely on a partial index in migration if strictly needed.
    },
    {
      fields: ['scope', 'scope_id']
    }
  ]
});

export default ConfigSetting;
