import { Request, Response } from 'express';
import { dealerExternalService } from '../services/dealerExternal.service';
import { ResponseHandler } from '../utils/responseHandler';
import logger from '../utils/logger';

export class DealerExternalController {
    /**
     * Search dealer by code via external API
     * GET /api/v1/dealers-external/search/:dealerCode
     */
    async searchByDealerCode(req: Request, res: Response): Promise<void> {
        try {
            const { dealerCode } = req.params;

            if (!dealerCode) {
                return ResponseHandler.error(res, 'Dealer code is required', 400);
            }

            const dealerInfo = await dealerExternalService.getDealerByCode(dealerCode);

            if (!dealerInfo) {
                return ResponseHandler.error(res, 'Dealer not found in external system', 404);
            }

            return ResponseHandler.success(res, dealerInfo, 'Dealer found successfully');
        } catch (error) {
            const errorMessage = error instanceof Error ? error.message : 'Unknown error';
            logger.error(`[DealerExternalController] Error searching dealer ${req.params.dealerCode}:`, error);
            return ResponseHandler.error(res, 'Failed to fetch dealer from external source', 500, errorMessage);
        }
    }
}

export const dealerExternalController = new DealerExternalController();
