const mongoose = require('mongoose');
const { tenantFields, applyPlatformPlugins } = require('../platformFields');
const { encryptJson, decryptJson } = require('@/services/integrations/secretStore');

const schema = new mongoose.Schema({
  ...tenantFields,
  provider: { type: String, enum: ['facebook', 'instagram', 'linkedin', 'x', 'whatsapp'], required: true },
  accountName: String,
  externalAccountId: String,
  credentialsEncrypted: mongoose.Schema.Types.Mixed,
  scopes: [String],
  status: { type: String, enum: ['connected', 'expired', 'disabled', 'error'], default: 'disabled' },
  lastCheckedAt: Date,
  error: String,
});

schema.virtual('credentials')
  .get(function getCredentials() {
    return decryptJson(this.credentialsEncrypted);
  })
  .set(function setCredentials(value) {
    this.credentialsEncrypted = encryptJson(value || {});
  });

module.exports = mongoose.model('SocialConnection', applyPlatformPlugins(schema));
