import mongoose from 'mongoose';
import mongoosePaginate from 'mongoose-paginate-v2';
import aggregatePaginate from 'mongoose-aggregate-paginate-v2';
import { MedicalEncryption } from '../utils/medicalEncryption';

const { Schema } = mongoose;

const QR_CODE_STATUS = ['ACTIVE', 'INACTIVE', 'MISSING'];

const QR_CODE_ACCESS_TYPE = ['PUBLIC', 'PRIVATE'];

const QR_CODE_TYPES = [
  'MEMORY_TAG',
  'MEDICAL_QR',
  'CAR',
  'LUGGAGE',
  'PET',
  'IDENTIFICATIONS',
  'DOCUMENT',
  'LINK',
  'WIFI',
];

const QRCodeSchema = new Schema(
  {
    title: { type: String, required: true },

    // QR Code type
    type: {
      type: String,
      enum: QR_CODE_TYPES,
      default: 'MEMORY_TAG',
    },

    // Standardized fields for all QR code types
    item_name: { type: String },
    item_description: { type: String },
    images: [
      {
        type: Schema.Types.ObjectId,
        ref: 'Media',
      },
    ],
    location: {
      type: Schema.Types.ObjectId,
      ref: 'Location',
      default: null,
    },
    location_enabled: { type: Boolean, default: false },
    name: { type: String },
    description: { type: JSON },
    lastKnownLocation: { type: String },
    notes: { type: String },
    memory_tag: {
      location: {
        type: Schema.Types.ObjectId,
        ref: 'Location',
        default: null,
      },
      // Enable/disable location tracking
      location_enabled: { type: Boolean, default: false },
      images: [
        {
          type: Schema.Types.ObjectId,
          ref: 'Media',
        },
      ],
    },

    // Type-specific details stored as JSON for flexibility
    type_details: {
      type: JSON,
      default: null, // store type-specific data (e.g., car: { plate_number: 'ABC-123', contact_preference: 'phone' })
    },

    isDelete: { type: Boolean, default: false },

    expired_at: { type: Date, default: null },

    // Track if expiration notification has been sent (for professional subscription daily expiration)
    expiration_notification_sent: { type: Boolean, default: false },
    expiration_notification_sent_at: { type: Date, default: null },

    status: {
      type: String,
      enum: QR_CODE_STATUS,
      default: 'ACTIVE',
    },

    created_by: {
      type: Schema.Types.ObjectId,
      ref: 'users',
      required: true,
    },

    access_type: {
      type: String,
      enum: QR_CODE_ACCESS_TYPE,
      default: 'PUBLIC',
    },

    pin: { type: String, default: null },
    pinHash: { type: String, default: null },

    color: { type: String, default: '#000000' },

    background_color: { type: String, default: '#FFFFFF' },

    size: { type: Number, default: 256 },

    // QR Privacy Controls
    privacy_controls: {
      // Public, Restricted (Required Password)
      access_level: {
        type: String,
        enum: ['PUBLIC', 'RESTRICTED'],
        default: 'PUBLIC',
      },
      // Password for restricted access
      access_password: { type: String, default: null },
      // Can disable at any point
      is_disabled: { type: Boolean, default: false },
      // Anonymous messaging allowed
      allow_anonymous_messaging: { type: Boolean, default: false },
      // Emergency notify feature
      emergency_notify: {
        enabled: { type: Boolean, default: false },
        contact_email: { type: String, default: null },
        contact_phone: { type: String, default: null },
      },
    },

    // Scan Analytics
    scan_count: {
      type: Number,
      default: 0,
    },
    scan_by_user: [
      {
        user_id: {
          type: Schema.Types.ObjectId,
          ref: 'users',
        },
        count: {
          type: Number,
          default: 0,
        },
      },
    ],
    anonymous_scan_count: {
      type: Number,
      default: 0,
    },
  },
  {
    timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' },
  }
);

// Essential indexes for better query performance
QRCodeSchema.index({ created_by: 1 });
QRCodeSchema.index({ status: 1 });
QRCodeSchema.index({ isDelete: 1 });
QRCodeSchema.index({ created_by: 1, status: 1, isDelete: 1 });
QRCodeSchema.index({ created_at: -1 });
// Scan analytics indexes
QRCodeSchema.index({ scan_count: -1 });
QRCodeSchema.index({ 'scan_by_user.user_id': 1 });
// Expiration tracking indexes for professional subscription daily expiration
QRCodeSchema.index({ expiration_notification_sent: 1, status: 1 });
QRCodeSchema.index({ expired_at: 1, status: 1 });

// Pre-save middleware to encrypt medical QR code type_details
QRCodeSchema.pre('save', function (next) {
  if (
    this.type === 'MEDICAL_QR' &&
    this.type_details &&
    typeof this.type_details !== 'string'
  ) {
    try {
      (this as any).type_details = MedicalEncryption.encryptMedicalData(
        this.type_details
      );
    } catch (error) {
      return next(error as Error);
    }
  }
  next();
});

// Pre-update middleware to encrypt medical QR code type_details
QRCodeSchema.pre(['findOneAndUpdate', 'updateOne', 'updateMany'], function (next) {
  const update = this.getUpdate() as any;

  if (update && update.type_details && update.type === 'MEDICAL_QR') {
    if (typeof update.type_details !== 'string') {
      try {
        update.type_details = MedicalEncryption.encryptMedicalData(update.type_details);
      } catch (error) {
        return next(error as Error);
      }
    }
  }

  // Handle $set operations
  if (
    update &&
    update.$set &&
    update.$set.type_details &&
    update.$set.type === 'MEDICAL_QR'
  ) {
    if (typeof update.$set.type_details !== 'string') {
      try {
        update.$set.type_details = MedicalEncryption.encryptMedicalData(
          update.$set.type_details
        );
      } catch (error) {
        return next(error as Error);
      }
    }
  }

  next();
});

// Add mongoose-paginate-v2 plugin for regular queries
QRCodeSchema.plugin(mongoosePaginate);
// Add mongoose-aggregate-paginate-v2 plugin for aggregation pipelines
QRCodeSchema.plugin(aggregatePaginate);

// Static method to check if user can create more QR codes
QRCodeSchema.statics.canUserCreateQRCode = async function (
  userId: string
): Promise<{
  canCreate: boolean;
  currentCount: number;
  limit: number;
  message?: string;
}> {
  const UserModel = mongoose.model('users');
  const { getQRCodeLimit } = require('../config/abilities');

  const user = await UserModel.findById(userId).select('subscription_tier').lean();

  if (!user) {
    return {
      canCreate: false,
      currentCount: 0,
      limit: 0,
      message: 'User not found',
    };
  }

  const limit = getQRCodeLimit((user as any).subscription_tier);
  const currentCount = await this.countDocuments({
    created_by: userId,
    isDelete: false,
  });

  const canCreate = currentCount < limit;

  return {
    canCreate,
    currentCount,
    limit,
    message: canCreate
      ? undefined
      : `QR code limit reached (${limit} for ${(user as any).subscription_tier} plan)`,
  };
};

const QRCodeModel = mongoose.model('QRCode', QRCodeSchema);
export default QRCodeModel;
