import mongoose from 'mongoose';

/**
 * SiteOfTheDayState Model
 * 
 * This model tracks the state of the "Site of the Day" selection logic.
 * It ensures deterministic, fair, and varied SOTD display on the homepage.
 * 
 * Features:
 * - Tracks the currently displayed SOTD
 * - Maintains a pending queue of tied winners
 * - Prevents consecutive day repetition
 * - Supports vote-based selection with tie handling
 */
const siteOfTheDayStateSchema = new mongoose.Schema({
  // Currently displayed Site of the Day
  currentSiteOfTheDay: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Award",
    default: null,
  },
  
  // Reference to the website ID for quick lookup
  currentWebsiteId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "WebsiteSubmission",
    default: null,
  },
  
  // When this SOTD was selected
  lastSelectionDate: {
    type: Date,
    default: null,
  },
  
  // Pending tied candidates from previous selections (ordered queue)
  // Stored as array of {websiteId, score, tiedDate}
  pendingSiteOfTheDayCandidates: [{
    websiteId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "WebsiteSubmission",
      required: true,
    },
    score: {
      type: Number,
      required: true,
    },
    tiedDate: {
      type: Date,
      required: true,
    },
    votesCount: {
      type: Number,
      default: 0,
    }
  }],
  
  // History of recently shown SOTDs to prevent repetition
  // Stores website IDs shown in the last 7 days
  recentlyShownWebsiteIds: [{
    websiteId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "WebsiteSubmission",
    },
    shownDate: {
      type: Date,
    }
  }],
  
  // Metadata for tracking and debugging
  lastUpdateReason: {
    type: String,
    enum: [
      'votes_winner',      // Selected based on highest votes yesterday
      'pending_queue',     // Selected from pending tied candidates
      'fallback',          // Fallback selection (no votes, no pending)
      'initialization',    // Initial setup
      'manual_override'    // Manual selection
    ],
    default: 'initialization',
  },
  
  // Statistics for monitoring
  statistics: {
    totalSelectionsFromVotes: { type: Number, default: 0 },
    totalSelectionsFromPending: { type: Number, default: 0 },
    totalFallbackSelections: { type: Number, default: 0 },
    lastCronRunDate: { type: Date, default: null },
  }
  
}, { timestamps: true });

// Index for performance
siteOfTheDayStateSchema.index({ lastSelectionDate: -1 });
siteOfTheDayStateSchema.index({ 'pendingSiteOfTheDayCandidates.websiteId': 1 });
siteOfTheDayStateSchema.index({ 'recentlyShownWebsiteIds.websiteId': 1 });

// Static method to get or create the singleton state
siteOfTheDayStateSchema.statics.getState = async function() {
  let state = await this.findOne();
  if (!state) {
    state = await this.create({
      lastUpdateReason: 'initialization',
      statistics: {
        totalSelectionsFromVotes: 0,
        totalSelectionsFromPending: 0,
        totalFallbackSelections: 0,
      }
    });
  }
  return state;
};

const SiteOfTheDayState = mongoose.model("SiteOfTheDayState", siteOfTheDayStateSchema);
export default SiteOfTheDayState;
