import express from "express";
import Award from "../models/award.js";
import Vote from "../models/vote.js";
import WebsiteSubmission from "../models/websiteSubmission.js";
import SiteOfTheDayState from "../models/siteOfTheDayState.js";
import {calculateAwards, selectSiteOfTheDay} from "./cronJobs.js";
//import { calculateAwards } from "../cronJobs.js"; 
const router = express.Router();

// Calculate and assign awards
// POST route - Manual trigger (reuses the same function)
router.post("/calculate-awards", async (req, res) => {
  try {
    const results = await calculateAwards();
    
    res.json({
      success: true,
      message: "Awards calculated successfully",
      results,
    });
  } catch (err) {
    console.error("Error calculating awards:", err);
    res.status(500).json({
      success: false,
      message: "Error calculating awards",
      error: err.message,
    });
  }
});

// GET all awards route (your existing route)
router.get("/", async (req, res) => {
  try {
    const { awardType, limit, page } = req.query;

    // Parse pagination parameters
    const limitNum = parseInt(limit) || 0;
    const pageNum = parseInt(page) || 1;

    let filter = {};
    if (awardType) {
      filter.awardType = awardType;
    }

    // Get total count for pagination
    const total = await Award.countDocuments(filter);

    // Build query with optional pagination
    let query = Award.find(filter)
      .populate({
        path: "websiteId",
        select:
          "createdAt URL ProfileType Submitted_URL Title Img Description Category Tags Colors Freelancer_Name Country",
        populate: [
          {
            path: "submittedBy",
            select: "userName"
          },
          {
            path: "Votes",
            select: "design usability creativity content score",
            populate: {
              path: "submittedBy",
              select: "userName"
            }
          }
        ]
      })
      .sort({ createdAt: -1 });

    // Apply pagination if limit is provided
    if (limitNum > 0) {
      query = query.limit(limitNum).skip((pageNum - 1) * limitNum);
    }

    const awards = await query;

    console.log(`Fetched awards : ${awards} `);
    
    res.json({
      success: true,
      count: awards.length,
      data: awards,
      pagination: limitNum > 0 ? {
        total,
        page: pageNum,
        limit: limitNum,
        pages: Math.ceil(total / limitNum)
      } : null
    });
  } catch (err) {
    console.error("Error fetching awards:", err);
    res.status(500).json({
      success: false,
      message: "Error fetching awards",
      error: err.message,
    });
  }
});

//RECENT SOTD 
// Get featured SOTD for homepage (enhanced with vote-based selection)
router.get("/sotd", async (req, res) => {
  try {
    // Get the current SOTD from state
    const state = await SiteOfTheDayState.getState();
    
    if (!state.currentSiteOfTheDay) {
      // No SOTD selected yet, trigger selection
      console.log('No SOTD state found, triggering selection...');
      await selectSiteOfTheDay();
      
      // Fetch the updated state
      const updatedState = await SiteOfTheDayState.getState();
      
      if (!updatedState.currentSiteOfTheDay) {
        // Still no SOTD, fallback to latest award
        return res.json({
          success: true,
          data: null,
          message: "No Site of the Day available yet",
          metadata: {
            isFromState: false,
            selectionReason: 'no_data'
          }
        });
      }
      
      // Fetch the award with populated data
      const featuredAward = await Award.findById(updatedState.currentSiteOfTheDay)
        .populate({
          path: "websiteId",
          select: "createdAt URL ProfileType Submitted_URL Title Img Description Category Colors Tags Freelancer_Name Country",
          populate: [
            { 
              path: "submittedBy", 
              select: "userName"
            },
            { 
              path: "Votes", 
              select: "design usability creativity content score submittedBy",
              populate: {
                path: "submittedBy",
                select: "userName"
              }
            }
          ]
        });
      
      return res.json({
        success: true,
        data: featuredAward,
        metadata: {
          isFromState: true,
          selectionReason: updatedState.lastUpdateReason,
          lastSelectionDate: updatedState.lastSelectionDate,
          pendingCandidatesCount: updatedState.pendingSiteOfTheDayCandidates.length,
          statistics: updatedState.statistics
        }
      });
    }
    
    // Fetch the current SOTD with populated data
    const featuredAward = await Award.findById(state.currentSiteOfTheDay)
      .populate({
        path: "websiteId",
        select: "createdAt URL ProfileType Submitted_URL Title Img Description Category Colors Tags Freelancer_Name Country",
        populate: [
          { 
            path: "submittedBy", 
            select: "userName"
          },
          { 
            path: "Votes", 
            select: "design usability creativity content score submittedBy",
            populate: {
              path: "submittedBy",
              select: "userName"
            }
          }
        ]
      });

    res.json({
      success: true,
      data: featuredAward,
      metadata: {
        isFromState: true,
        selectionReason: state.lastUpdateReason,
        lastSelectionDate: state.lastSelectionDate,
        pendingCandidatesCount: state.pendingSiteOfTheDayCandidates.length,
        statistics: state.statistics
      }
    });

  } catch (err) {
    console.error("Error fetching featured SOTD:", err);
    res.status(500).json({
      success: false,
      message: "Error fetching featured SOTD",
      error: err.message,
    });
  }
});

// Manual trigger for SOTD selection (for testing/debugging)
router.post("/sotd/select", async (req, res) => {
  try {
    console.log('Manual SOTD selection triggered...');
    const result = await selectSiteOfTheDay();
    
    res.json({
      success: true,
      message: "SOTD selection completed",
      result
    });
  } catch (err) {
    console.error("Error in manual SOTD selection:", err);
    res.status(500).json({
      success: false,
      message: "Error selecting SOTD",
      error: err.message,
    });
  }
});

// Get SOTD state information (for debugging)
router.get("/sotd/state", async (req, res) => {
  try {
    const state = await SiteOfTheDayState.getState();
    
    res.json({
      success: true,
      state: {
        currentWebsiteId: state.currentWebsiteId,
        lastSelectionDate: state.lastSelectionDate,
        lastUpdateReason: state.lastUpdateReason,
        pendingCandidatesCount: state.pendingSiteOfTheDayCandidates.length,
        pendingCandidates: state.pendingSiteOfTheDayCandidates,
        recentlyShownCount: state.recentlyShownWebsiteIds.length,
        statistics: state.statistics
      }
    });
  } catch (err) {
    console.error("Error fetching SOTD state:", err);
    res.status(500).json({
      success: false,
      message: "Error fetching SOTD state",
      error: err.message,
    });
  }
});

export default router;
