/**
 * API Route: Verify block integrity
 * GET /api/transport/verify/[blockHash]
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getTransportChain } from '../../../../lib/transport/tracker';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'GET') {
    return res.status(405).json({ success: false, error: 'Method not allowed' });
  }

  try {
    const { blockHash } = req.query;

    if (!blockHash || typeof blockHash !== 'string') {
      return res.status(400).json({
        success: false,
        error: 'Block hash is required'
      });
    }

    const transportChain = getTransportChain();

    // Find the block with the given hash
    const block = transportChain.chain.find(b => b.hash === blockHash);

    if (!block) {
      return res.status(404).json({
        success: false,
        error: `Block not found with hash: ${blockHash}`
      });
    }

    // Verify chain integrity
    const isChainValid = transportChain.isChainValid();

    // Verify this specific block's position in chain
    const blockIndex = transportChain.chain.findIndex(b => b.hash === blockHash);
    const previousBlock = blockIndex > 0 ? transportChain.chain[blockIndex - 1] : null;
    const isBlockValid = previousBlock ? block.previousHash === previousBlock.hash : block.index === 0;

    res.status(200).json({
      success: true,
      data: {
        block: {
          index: block.index,
          hash: block.hash,
          previousHash: block.previousHash,
          timestamp: block.timestamp,
          eventType: block.transportEvent.eventType,
          eventId: block.transportEvent.id
        },
        verification: {
          isChainValid,
          isBlockValid,
          blockPosition: blockIndex,
          totalBlocks: transportChain.chain.length
        }
      }
    });
  } catch (error: any) {
    console.error('Error verifying block:', error);
    res.status(500).json({ success: false, error: error.message || 'Internal server error' });
  }
}
