import { DataTypes } from 'sequelize';
import sequelize from '../database.js';
import { encryptData, decryptData } from '../utils/encrypt.js';

const ClickTtAccount = sequelize.define('ClickTtAccount', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false
  },
  userId: {
    type: DataTypes.INTEGER,
    allowNull: false,
    unique: true,
    references: {
      model: 'user',
      key: 'id'
    },
    onDelete: 'CASCADE',
    field: 'user_id'
  },
  username: {
    type: DataTypes.STRING,
    allowNull: false,
    set(value) {
      this.setDataValue('username', encryptData(value));
    },
    get() {
      const encryptedValue = this.getDataValue('username');
      return encryptedValue ? decryptData(encryptedValue) : null;
    }
  },
  encryptedPassword: {
    type: DataTypes.TEXT('long'),
    allowNull: true,
    field: 'encrypted_password'
  },
  savePassword: {
    type: DataTypes.BOOLEAN,
    defaultValue: false,
    allowNull: false,
    field: 'save_password'
  },
  lastLoginAttempt: {
    type: DataTypes.DATE,
    allowNull: true,
    field: 'last_login_attempt'
  },
  lastLoginSuccess: {
    type: DataTypes.DATE,
    allowNull: true,
    field: 'last_login_success'
  },
  playwrightStorageState: {
    type: DataTypes.TEXT('long'),
    allowNull: true,
    field: 'playwright_storage_state',
    set(value) {
      if (value === null || value === undefined) {
        this.setDataValue('playwrightStorageState', null);
      } else {
        const jsonString = typeof value === 'string' ? value : JSON.stringify(value);
        this.setDataValue('playwrightStorageState', encryptData(jsonString));
      }
    },
    get() {
      const encrypted = this.getDataValue('playwrightStorageState');
      if (!encrypted) return null;
      try {
        return JSON.parse(decryptData(encrypted));
      } catch (_err) {
        return null;
      }
    }
  }
}, {
  underscored: true,
  tableName: 'click_tt_account',
  timestamps: true,
  hooks: {
    beforeSave: async (instance) => {
      if (!instance.savePassword) {
        instance.encryptedPassword = null;
      }
    }
  }
});

ClickTtAccount.prototype.setPassword = function(password) {
  if (password && this.savePassword) {
    this.encryptedPassword = encryptData(password);
  } else {
    this.encryptedPassword = null;
  }
};

ClickTtAccount.prototype.getPassword = function() {
  if (!this.encryptedPassword) return null;
  try {
    return decryptData(this.encryptedPassword);
  } catch (_err) {
    return null;
  }
};

export default ClickTtAccount;
