/**
 * Feature Request Notification Log Model
 *
 * Append-only log of every email notification sent (or attempted) for feature
 * request activity. One document per notification dispatch — if a single
 * activity triggers emails to 5 recipients, that is still one log entry with
 * all 5 addresses in `recipients`.
 *
 * This exists so the Super Admin can review what was sent, when, and whether
 * it succeeded — without leaving the Settings page.
 */

import mongoose, { Schema, Document } from 'mongoose';

export type FeatureRequestActivityType =
  | 'created'
  | 'status_update'
  | 'approved'
  | 'rejected'
  | 'done'
  | 'comment_added'
  | 'edited'
  | 'withdrawn'
  | 'deleted';

export interface IFeatureRequestNotificationLog extends Document {
  featureRequestId: string;
  activityType: FeatureRequestActivityType;
  triggeredByUserId: string;
  triggeredByUserName: string;
  triggeredByUserRole: string;
  featureRequestTitle: string;
  recipients: string[];
  subject: string;
  success: boolean;
  error?: string;
  messageId?: string;
  skipped?: boolean;
  createdAt: Date;
}

const FeatureRequestNotificationLogSchema = new Schema<IFeatureRequestNotificationLog>({
  featureRequestId: {
    type: String,
    required: [true, 'Feature request ID is required'],
    index: true,
  },
  activityType: {
    type: String,
    required: [true, 'Activity type is required'],
    enum: ['created', 'status_update', 'approved', 'rejected', 'done', 'comment_added', 'edited', 'withdrawn', 'deleted'],
  },
  triggeredByUserId: {
    type: String,
    required: [true, 'Triggered by user ID is required'],
  },
  triggeredByUserName: {
    type: String,
    default: 'Unknown',
  },
  triggeredByUserRole: {
    type: String,
    default: 'user',
  },
  featureRequestTitle: {
    type: String,
    default: '',
  },
  recipients: {
    type: [String],
    required: [true, 'At least one recipient is required'],
  },
  subject: {
    type: String,
    default: '',
  },
  success: {
    type: Boolean,
    default: false,
  },
  error: {
    type: String,
  },
  messageId: {
    type: String,
  },
  skipped: {
    type: Boolean,
    default: false,
  },
}, {
  timestamps: false, // only createdAt needed; no updatedAt on append-only logs
  versionKey: false,
});

// Efficient lookups
FeatureRequestNotificationLogSchema.index({ featureRequestId: 1, createdAt: -1 });
FeatureRequestNotificationLogSchema.index({ createdAt: -1 });
FeatureRequestNotificationLogSchema.index({ activityType: 1 });

export const FeatureRequestNotificationLog =
  mongoose.models.FeatureRequestNotificationLog ||
  mongoose.model<IFeatureRequestNotificationLog>('FeatureRequestNotificationLog', FeatureRequestNotificationLogSchema);