import express from "express";
import PostJob from "../models/postJob.js";
import { authenticate } from "../middleware/authMiddleware.js";
import { verifyPayPalOrder } from "../middleware/paypalVerification.js";
import { sendJobSubmissionEmail } from "../utils/emailService.js";
import { User } from "../models/user.js";
import { uploadToDropbox, generateUniqueFilename, getFileExtensionFromBase64 } from "../utils/dropboxService.js";
import { getPrice } from "../config/pricing.js";

const router = express.Router();

// ✅ PHASE 1: Create pending job posting (no payment required yet)
router.post("/create", authenticate, async (req, res) => {
  try {
    console.log('📝 Job post submission (PENDING) request received');

    const {
      title,
      description,
      skills,
      type,
      category,
      gender,
      experience,
      languages,
      companyName,
      companyWebsite,
      logo,
      apply,
      company,
      country,
    } = req.body;

    // Extract data from nested objects
    const applyMethod = apply?.method || '';
    const applyEmail = apply?.email || '';
    const applyUrl = apply?.url || '';

    const companyEmail = company?.companyEmail || '';
    const companyContact = company?.contact || '';
    const hideCompanyEmail = company?.hideEmail || false;
    const hideCompanyContact = company?.hideContact || false;

    const companyLogo = logo;

    // Validate required fields
    if (!title || !companyName || !companyWebsite || !companyLogo || !companyContact) {
      return res.status(400).json({
        ok: false,
        error: "VALIDATION_ERROR",
        message: "Missing required fields",
        received: {
          title: !!title,
          companyName: !!companyName,
          companyWebsite: !!companyWebsite,
          companyLogo: !!companyLogo,
          companyContact: !!companyContact
        }
      });
    }

    // ✅ Upload company logo to Dropbox
    let companyLogoUrl;
    if (companyLogo) {
      const extension = getFileExtensionFromBase64(companyLogo);
      const filename = generateUniqueFilename(`${companyName}-logo.${extension}`, 'job-posting');
      companyLogoUrl = await uploadToDropbox(companyLogo, filename, '/job-postings');
      console.log('✅ Company logo uploaded to Dropbox:', companyLogoUrl);
    }

    // Create the payload with PENDING status - no payment info yet
    const payload = {
      submittedBy: req.user.id,
      title,
      description,
      skills,
      type,
      category,
      gender,
      experience,
      languages,
      applyMethod,
      applyEmail,
      applyUrl,
      companyName,
      companyWebsite,
      companyLogo: companyLogoUrl,
      country,
      companyEmail,
      companyContact,
      hideCompanyEmail,
      hideCompanyContact,
      status: 'pending_payment',
      // ✅ Generate temporary unique paymentOrderID to avoid null duplicate key errors
      paymentOrderID: `PENDING_JOB_${Date.now()}_${req.user.id}_${Math.random().toString(36).substr(2, 9)}`,
    };

    // Save the pending job posting to the database
    const doc = await PostJob.create(payload);

    console.log("✅ Pending job posting created: " + doc._id);

    // Get the price for this service
    const servicePrice = getPrice('jobPost');

    return res.status(201).json({
      ok: true,
      data: doc,
      price: servicePrice,
      message: "Job posting created successfully. Please complete payment to publish."
    });
  } catch (error) {
    console.error("❌ Pending job posting error:", error);

    if (error.name === 'ValidationError') {
      return res.status(400).json({
        ok: false,
        error: "VALIDATION_ERROR",
        message: "Validation error",
        errors: error.errors
      });
    }

    return res.status(500).json({
      ok: false,
      error: "SERVER_ERROR",
      message: error.message
    });
  }
});

// ✅ PHASE 2: Confirm payment and publish job posting
router.post("/confirm-payment", authenticate, async (req, res) => {
  try {
    const userId = req.user.id;

    console.log('💳 Job posting payment confirmation request received');

    const {
      submissionId,
      paymentOrderID,
      paymentAmount,
      couponCode,
      isFreeSubmission,
    } = req.body;

    if (!submissionId) {
      return res.status(400).json({
        ok: false,
        error: "SUBMISSION_ID_REQUIRED",
        message: "Submission ID is required"
      });
    }

    // Find the pending submission
    const submission = await PostJob.findById(submissionId);

    if (!submission) {
      return res.status(404).json({
        ok: false,
        error: "SUBMISSION_NOT_FOUND",
        message: "Submission not found"
      });
    }

    // Verify the submission belongs to the current user
    if (submission.submittedBy.toString() !== userId.toString()) {
      return res.status(403).json({
        ok: false,
        error: "UNAUTHORIZED",
        message: "You are not authorized to confirm payment for this submission"
      });
    }

    // Check if submission is already published
    if (submission.status === 'published') {
      return res.status(400).json({
        ok: false,
        error: "ALREADY_PUBLISHED",
        message: "This submission has already been published"
      });
    }

    // ✅ CRITICAL: Check if this is a free submission (price = 0 due to coupon)
    const isFree = isFreeSubmission === true && paymentAmount === 0;

    let order = null;

    if (isFree) {
      // For free submissions, verify coupon instead of payment
      if (!couponCode) {
        return res.status(400).json({
          ok: false,
          error: "COUPON_REQUIRED",
          message: "Coupon code is required for free submission"
        });
      }

      console.log('🎟️ Processing free job posting with coupon:', couponCode);

      // Update submission with coupon info
      submission.paymentOrderID = `FREE_JOB_${Date.now()}_${userId}`;
      submission.paymentStatus = 'FREE_COUPON';
      submission.paymentAmount = 0;
      submission.paymentCurrency = 'USD';
      submission.paymentDate = new Date();
      submission.paymentVerified = true;
      submission.couponCode = couponCode;
      submission.isFreeSubmission = true;
      submission.status = 'published';

    } else {
      // Regular paid submission - verify PayPal payment
      if (!paymentOrderID) {
        submission.status = 'payment_failed';
        await submission.save();

        return res.status(400).json({
          ok: false,
          error: "PAYMENT_REQUIRED",
          message: "Payment order ID is required for submission",
          canRetry: true,
          submissionId: submission._id
        });
      }

      // Check if this payment has already been used
      const existingPayment = await PostJob.findOne({
        paymentOrderID,
        _id: { $ne: submissionId }
      });
      if (existingPayment) {
        console.log(`Payment ID already exists: ${paymentOrderID}`);
        return res.status(409).json({
          ok: false,
          error: "PAYMENT_ALREADY_USED",
          message: "This payment has already been used for another submission"
        });
      }

      // Verify payment with PayPal
      console.log('🔍 Verifying PayPal payment:', paymentOrderID);
      const verificationResult = await verifyPayPalOrder(paymentOrderID);

      if (!verificationResult.success) {
        submission.status = 'payment_failed';
        await submission.save();

        return res.status(400).json({
          ok: false,
          error: "PAYMENT_VERIFICATION_FAILED",
          message: "Payment verification failed. Please try again.",
          canRetry: true,
          submissionId: submission._id
        });
      }

      order = verificationResult.order;

      // Check if payment is completed or approved
      if (order.status !== 'COMPLETED' && order.status !== 'APPROVED') {
        submission.status = 'payment_failed';
        await submission.save();

        return res.status(400).json({
          ok: false,
          error: "PAYMENT_NOT_COMPLETED",
          message: `Payment status is ${order.status}. Expected COMPLETED or APPROVED.`,
          canRetry: true,
          submissionId: submission._id
        });
      }

      // Update submission with payment info
      submission.paymentOrderID = order.id;
      submission.paymentStatus = order.status;
      submission.paymentAmount = parseFloat(order.amount);
      submission.paymentCurrency = order.currency;
      submission.payerEmail = order.payerEmail;
      submission.payerName = order.payerName;
      submission.paymentDate = new Date();
      submission.paymentVerified = true;
      submission.isFreeSubmission = false;
      submission.status = 'published';
    }

    // Save the updated submission
    await submission.save();

    console.log(isFree
      ? "✅ Free job posting published with coupon: " + couponCode
      : "✅ Job posting published with verified payment: " + submission._id
    );

    // Apply coupon if this is a free submission
    if (isFree && couponCode) {
      try {
        const response = await fetch(`${process.env.API_Dep_URL || 'http://localhost:5000'}/api/coupons/apply`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': req.headers.authorization,
          },
          body: JSON.stringify({
            couponCode: couponCode,
            serviceType: 'jobPost',
          }),
        });

        if (response.ok) {
          console.log('✅ Coupon applied successfully:', couponCode);
        } else {
          console.warn('⚠️ Failed to apply coupon, but submission completed:', couponCode);
        }
      } catch (couponError) {
        console.error('❌ Error applying coupon:', couponError.message);
      }
    }

    // Get user information for email
    const user = await User.findById(userId);

    // Send confirmation email
    if (user && user.email) {
      console.log("📧 Attempting to send confirmation email to:", user.email);
      try {
        await sendJobSubmissionEmail(user.email, {
          userName: user.userName || user.name || "User",
          jobTitle: submission.title,
          companyName: submission.companyName,
          jobType: submission.type,
          category: submission.category,
          submissionDate: new Date(),
          paymentOrderID: isFree ? 'FREE (Coupon Applied)' : order?.id,
          paymentAmount: isFree ? '0.00' : order?.amount,
          paymentCurrency: 'USD',
        });
        console.log("✅ Confirmation email sent successfully");
      } catch (emailError) {
        console.error("❌ Failed to send confirmation email:", emailError.message);
      }
    }

    return res.status(200).json({
      ok: true,
      data: submission,
      message: "Payment confirmed and job posting published successfully!"
    });
  } catch (error) {
    console.error("❌ Job posting payment confirmation error:", error);
    return res.status(500).json({
      ok: false,
      error: "SERVER_ERROR",
      message: error.message
    });
  }
});

// GET: Get all job posts - only published
router.get("/", async (req, res) => {
  try {
    const { category, type, country } = req.query;

    let filter = {
      // ✅ Show published submissions OR old submissions without status field
      $or: [
        { status: 'published' },
        { status: { $exists: false } } // Old submissions before status field was added
      ]
    };

    if (category) filter.category = category;
    if (type) filter.type = type;
    if (country) filter.country = country;

    const posts = await PostJob.find(filter).populate("submittedBy", "userName");
    res.status(200).json(posts);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "Error fetching job posts." });
  }
});

// GET: Get a job post by ID
router.get("/:id", async (req, res) => {
  const { id } = req.params;
  try {
    const post = await PostJob.findById(id).populate("submittedBy", "userName");
    if (!post) {
      return res.status(404).json({ message: "Job post not found." });
    }
    res.status(200).json(post);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "Error fetching job post." });
  }
});

export default router;
