const { pool } = require("../../config/db");

const getAllGatePasses = async (req, res) => {
  try {
    const orgId = req.session?.user?.orgId;

    const page = Number(req.query.page) || 1;

    const limit = Number(req.query.limit) || 10;

    const search = req.query.search || "";

    const offset = (page - 1) * limit;

    // =========================================
    // SEARCH FILTER
    // =========================================

    let searchQuery = "";

    const values = [orgId];

    if (search) {
      values.push(`%${search}%`);

      searchQuery = `
        AND (
          gp.pass_number ILIKE $2
          OR cv.sales_order_number ILIKE $2
          OR cv.vehicle_number ILIKE $2
          OR cv.driver_name ILIKE $2
        )
      `;
    }

    // =========================================
    // TOTAL COUNT
    // =========================================

    const totalQuery = `
      SELECT COUNT(*) AS total

      FROM gate_passes gp

      LEFT JOIN commercial_vehicles cv
        ON cv.id = gp.commercial_vehicle_id

      WHERE gp.org_id = $1
AND gp.is_deleted = false

      ${searchQuery}
    `;

    const totalResult = await pool.query(totalQuery, values);

    const total = Number(totalResult.rows[0].total);

    // =========================================
    // PAGINATION VALUES
    // =========================================

    values.push(limit);

    values.push(offset);

    const limitIndex = values.length - 1;

    const offsetIndex = values.length;

    // =========================================
    // FETCH DATA
    // =========================================

    const query = `
      SELECT
        gp.id,
        gp.pass_number,
        gp.pass_type,
        gp.pass_status,
        gp.generated_at,
        gp.exited_at,

        cv.vehicle_number,
        cv.driver_name,
        cv.driver_number,

        cv.sales_order_number,

        cv.source_type,

        sd.shipment_number,
        sd.shipment_status

      FROM gate_passes gp

      LEFT JOIN commercial_vehicles cv
        ON cv.id = gp.commercial_vehicle_id

      LEFT JOIN shipment_dispatches sd
        ON sd.vehicle_id = cv.id

      WHERE gp.org_id = $1
AND gp.is_deleted = false

      ${searchQuery}

      ORDER BY gp.id DESC

      LIMIT $${limitIndex}
      OFFSET $${offsetIndex}
    `;

    const result = await pool.query(query, values);

    return res.status(200).json({
      success: true,

      data: result.rows,

      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error("GET GATE PASSES ERROR:", error);

    return res.status(500).json({
      success: false,
      message: "Failed to fetch gate passes",
      error: error.message,
    });
  }
};

const getGatePassById = async (req, res) => {
  try {
    const { id } = req.params;

    const orgId = req.session?.user?.orgId;

    const query = `
      SELECT
        gp.id,
        gp.pass_number,
        gp.pass_type,
        gp.pass_status,
        gp.generated_at,
        gp.exited_at,

        cv.id AS vehicle_id,
        cv.vehicle_number,
        cv.vehicle_type,

        cv.driver_name,
        cv.driver_number,

        cv.gate_status,
        cv.entry_time,
        cv.exit_time,

        cv.sales_order_number,
        cv.reference_no,

        cv.customer_name,

        cv.weighbridge_status,
        cv.qc_status,

        sd.id AS shipment_id,
        sd.shipment_number,
        sd.shipment_status,
        sd.return_weight_done,
        sd.qc_done

      FROM gate_passes gp

      LEFT JOIN commercial_vehicles cv
        ON cv.id = gp.commercial_vehicle_id

      LEFT JOIN shipment_dispatches sd
        ON sd.vehicle_id = cv.id

      WHERE gp.id = $1
      AND gp.org_id = $2
    `;

    const result = await pool.query(query, [id, orgId]);

    if (result.rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: "Gate pass not found",
      });
    }

    return res.status(200).json({
      success: true,
      data: result.rows[0],
    });
  } catch (error) {
    console.error("GET GATE PASS BY ID ERROR:", error);

    return res.status(500).json({
      success: false,
      message: "Failed to fetch gate pass",
      error: error.message,
    });
  }
};

const deleteGatePass = async (req, res) => {
  try {
    const { id } = req.params;

    const orgId = req.session?.user?.orgId;

    // =========================================
    // CHECK EXISTING
    // =========================================

    const existingResult = await pool.query(
      `
      SELECT *
      FROM gate_passes
      WHERE id = $1
      AND org_id = $2
      AND is_deleted = false
      `,
      [id, orgId],
    );

    if (existingResult.rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: "Gate pass not found",
      });
    }

    const gatePass = existingResult.rows[0];

    // =========================================
    // PREVENT DELETE AFTER EXIT
    // =========================================

    if (gatePass.pass_status === "EXITED") {
      return res.status(400).json({
        success: false,
        message: "Exited gate passes cannot be deleted",
      });
    }

    // =========================================
    // SOFT DELETE
    // =========================================

    await pool.query(
      `
      UPDATE gate_passes

      SET
        is_deleted = true,
        updated_at = NOW()

      WHERE id = $1
      `,
      [id],
    );

    return res.status(200).json({
      success: true,
      message: "Gate pass deleted successfully",
    });
  } catch (error) {
    console.error("DELETE GATE PASS ERROR:", error);

    return res.status(500).json({
      success: false,
      message: "Failed to delete gate pass",
      error: error.message,
    });
  }
};

const generateGatePassPDF = require("../../services/pdf/generateGatePassPDF");
const downloadGatePassPDF = async (req, res) => {
  try {
    const { id } = req.params;

    const orgId = req.session?.user?.orgId;

    // =====================================================
    // FETCH GATE PASS
    // =====================================================

    const query = `
      SELECT
        gp.id,
        gp.pass_number,
        gp.pass_type,
        gp.pass_status,
        gp.generated_at,
        gp.exited_at,

        cv.id AS vehicle_id,
        cv.vehicle_number,
        cv.vehicle_type,

        cv.driver_name,
        cv.driver_number,

        cv.gate_status,
        cv.time_in,
        cv.exit_time,

        cv.sales_order_number,
        cv.reference_no,

        cv.customer_name,

        cv.weighbridge_status,
        cv.qc_status,

        sd.id AS shipment_id,
        sd.shipment_number,
        sd.shipment_status,

        u.name AS created_by_name

      FROM gate_passes gp

      LEFT JOIN commercial_vehicles cv
        ON cv.id = gp.commercial_vehicle_id

      LEFT JOIN shipment_dispatches sd
        ON sd.vehicle_id = cv.id

      LEFT JOIN users u
        ON u.id = gp.generated_by

      WHERE gp.id = $1
      AND gp.org_id = $2
      AND gp.is_deleted = false
    `;

    const result = await pool.query(query, [
      id,
      orgId,
    ]);

    // =====================================================
    // NOT FOUND
    // =====================================================

    if (result.rows.length === 0) {
      return res.status(404).json({
        success: false,
        message: "Gate pass not found",
      });
    }

    const gatePass = result.rows[0];

    // =====================================================
    // GENERATE PDF
    // =====================================================

    const pdfBuffer =
      await generateGatePassPDF(gatePass);

    // =====================================================
    // RESPONSE HEADERS
    // =====================================================

    res.setHeader(
      "Content-Type",
      "application/pdf"
    );

    res.setHeader(
      "Content-Disposition",
      `attachment; filename=${gatePass.pass_number}.pdf`
    );

    // =====================================================
    // SEND PDF
    // =====================================================

    return res.send(pdfBuffer);

  } catch (error) {
    console.error(
      "DOWNLOAD GATE PASS PDF ERROR:",
      error
    );

    return res.status(500).json({
      success: false,
      message: "Failed to download gate pass PDF",
      error: error.message,
    });
  }
};

module.exports = {
  getAllGatePasses,
  getGatePassById,
  deleteGatePass,
  downloadGatePassPDF,
};
