const Tesseract = require('tesseract.js');
const fs = require('fs');

// Handle PAN verification logic
const verifyPan = async (req, res) => {
  const userPan = req.body.pan;
  const imagePath = req.file.path;

  try {
    const { data: { text } } = await Tesseract.recognize(imagePath, 'eng');

    // Regex to extract PAN format: 5 letters, 4 digits, 1 letter
    const extractedPan = text.match(/[A-Z]{5}[0-9]{4}[A-Z]{1}/);

    // Delete the uploaded file after processing
    fs.unlinkSync(imagePath);

    if (extractedPan && extractedPan[0] === userPan.toUpperCase()) {
      return res.json({ verified: true, extractedPan: extractedPan[0] });
    } else {
      return res.json({ verified: false, extractedPan: extractedPan ? extractedPan[0] : null });
    }
  } catch (err) {
    // Clean up and respond with an error if any issues arise
    fs.unlinkSync(imagePath);
    return res.status(500).json({ error: 'Error processing image', details: err.message });
  }
};

module.exports = { verifyPan };
