import express from 'express';
//import PostJob from './models/PostJob'; // Make sure the model path is correct
import PostJob from '../models/postJob.js'
// import firebaseAuth from '../middleware/firebaseAuth'; // Firebase authentication middleware (make sure it's set up)

const router = express.Router();

// Route to submit a new job post (POST)
router.post("/submit", async (req, res) => {
  try {
    // Destructure incoming request body
    const {
      title,
      description,
      skills,
      type,
      category,
      gender,
      experience,
      languages,
      byEmail,
      byUrl,
      name,
      website,
      email,
      contactNo,
      companyLogo,
    } = req.body;

    // Create a new job post instance
    const newJobPost = new PostJob({
      submittedBy: req.user._id,  // assuming user is authenticated and their _id is in req.user
      title,
      description,
      skills,
      type,
      category,
      gender,
      experience,
      languages,
      byEmail,
      byUrl,
      name,
      website,
      email,
      contactNo,
      companyLogo,
    });

    // Save the job post to the database
    await newJobPost.save();
    res.status(201).json({
      message: 'Job post created successfully',
      data: newJobPost,
    });
  } catch (err) {
    res.status(400).json({
      message: 'Error submitting job post',
      error: err.message,
    });
  }
});

// Route to get all job posts (GET)
// Route to get all job posts with optional filters (GET)
router.get("/all", async (req, res) => {
  try {
    // Destructure query params (category, type, country)
    const { category, type, country } = req.query;

    let filter = {}; // Empty filter means "no filter" (all posts)

    // Add filters to the query if provided
    if (category) filter.category = category;
    if (type) filter.type = type;
    if (country) filter.country = country;

    // Find job posts based on the filter
    const jobPosts = await PostJob.find(filter)
      .populate('submittedBy', 'name avatar') // Populate user info (name, avatar)
      .sort({ createdAt: -1 }); // Sort by newest first

    res.status(200).json({
      data: jobPosts,
    });
  } catch (err) {
    res.status(500).json({
      message: 'Error fetching job posts',
      error: err.message,
    });
  }
});

// Route to get a specific job post by ID (GET)
router.get("/:id", async (req, res) => {
  try {
    const jobPost = await PostJob.findById(req.params.id)
      .populate('submittedBy', 'name avatar'); // Populate the user who submitted the job post

    if (!jobPost) {
      return res.status(404).json({
        message: "Job post not found",
      });
    }

    res.status(200).json({
      data: jobPost,
    });
  } catch (err) {
    res.status(500).json({
      message: 'Error fetching job post',
      error: err.message,
    });
  }
});

export default router;
