const mongoose = require('mongoose');
const { tenantFields, applyPlatformPlugins } = require('../platformFields');

const deliveryStatusSchema = new mongoose.Schema(
  {
    inApp: { type: String, enum: ['pending', 'delivered', 'failed'], default: 'delivered' },
    email: { type: String, enum: ['pending', 'delivered', 'failed', 'skipped'], default: 'skipped' },
    whatsapp: { type: String, enum: ['pending', 'delivered', 'failed', 'skipped'], default: 'skipped' },
  },
  { _id: false }
);

const schema = new mongoose.Schema({
  ...tenantFields,
  recipient: { type: mongoose.Schema.ObjectId, ref: 'Admin', required: true, index: true },
  type: { type: String, required: true, index: true },
  eventKey: { type: String, index: true },
  title: { type: String, required: true },
  message: { type: String, required: true },
  severity: { type: String, enum: ['info', 'success', 'warning', 'error'], default: 'info' },
  entityType: String,
  entityId: mongoose.Schema.Types.ObjectId,
  actionUrl: String,
  channels: [{ type: String, enum: ['in_app', 'email', 'whatsapp'] }],
  readAt: Date,
  deliveredAt: Date,
  deliveryStatus: { type: deliveryStatusSchema, default: () => ({}) },
  deliveryLog: [{ channel: String, status: String, message: String, deliveredAt: Date }],
  expiresAt: Date,
});

schema.index({ tenant: 1, recipient: 1, eventKey: 1 }, { unique: true, partialFilterExpression: { eventKey: { $exists: true, $type: 'string' } } });

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