const express = require('express');
const multer = require('multer');
const tesseract = require('tesseract.js');
const fs = require('fs');
const path = require('path');

// Configure multer for file upload
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, './uploads/pan/');
  },
  filename: (req, file, cb) => {
    const timestamp = Date.now();
    cb(null, `${timestamp}-${file.originalname}`);
  },
});

const upload = multer({ storage });

const router = express.Router();

// Basic PAN format validation (simple regex)
const isValidPan = (pan) => {
  const panRegex = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/;
  return panRegex.test(pan);
};

// Verify PAN number and compare with image text
router.post('/verify', upload.single('panImage'), async (req, res) => {
  try {
    const { pan } = req.body;
    const imagePath = req.file.path;  // Path to the uploaded image
    console.log('Received PAN:', pan);
    console.log('Image Path:', imagePath);

    // Validate PAN format
    if (!isValidPan(pan)) {
      return res.status(400).json({ message: 'Invalid PAN format' });
    }

    // Perform OCR on the uploaded image to extract the text
    const result = await tesseract.recognize(imagePath, 'eng', {
      logger: (m) => console.log(m),
    });

    const extractedText = result.data.text.trim(); // The text extracted from the image
    console.log('Extracted PAN from image:', extractedText);

    // Compare the extracted text with the provided PAN number
    if (extractedText === pan) {
      res.status(200).json({ message: 'PAN verified successfully' });
    } else {
      res.status(400).json({ message: 'PAN number does not match the uploaded image' });
    }

    // Clean up the uploaded image file after processing (optional)
    fs.unlinkSync(imagePath);
  } catch (error) {
    console.error('Error during PAN verification:', error);
    res.status(500).json({ message: 'Error verifying PAN' });
  }
});

module.exports = router;
