import { Request, Response } from 'express';
import type { AuthenticatedRequest } from '../types/express';
import * as dealerService from '../services/dealer.service';
import { ResponseHandler } from '../utils/responseHandler';
import logger from '../utils/logger';

export class DealerController {
  /**
   * Get all dealers
   * GET /api/v1/dealers?q=searchTerm&limit=10 (optional search and limit)
   */
  async getAllDealers(req: Request, res: Response): Promise<void> {
    try {
      const searchTerm = req.query.q as string | undefined;
      const limitParam = req.query.limit as string | undefined;
      // Parse limit, default to 10, max 100
      const limit = limitParam ? Math.min(Math.max(1, parseInt(limitParam, 10)), 100) : 10;
      const dealers = await dealerService.getAllDealers(searchTerm, limit);
      return ResponseHandler.success(res, dealers, 'Dealers fetched successfully');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      logger.error('[DealerController] Error fetching dealers:', error);
      return ResponseHandler.error(res, 'Failed to fetch dealers', 500, errorMessage);
    }
  }

  /**
   * Get dealer by code
   * GET /api/v1/dealers/code/:dealerCode
   */
  async getDealerByCode(req: Request, res: Response): Promise<void> {
    try {
      const { dealerCode } = req.params;
      const dealer = await dealerService.getDealerByCode(dealerCode);

      if (!dealer) {
        return ResponseHandler.error(res, 'Dealer not found', 404);
      }

      return ResponseHandler.success(res, dealer, 'Dealer fetched successfully');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      logger.error('[DealerController] Error fetching dealer by code:', error);
      return ResponseHandler.error(res, 'Failed to fetch dealer', 500, errorMessage);
    }
  }

  /**
   * Get dealer by email
   * GET /api/v1/dealers/email/:email
   */
  async getDealerByEmail(req: Request, res: Response): Promise<void> {
    try {
      const { email } = req.params;
      const dealer = await dealerService.getDealerByEmail(email);

      if (!dealer) {
        return ResponseHandler.error(res, 'Dealer not found', 404);
      }

      return ResponseHandler.success(res, dealer, 'Dealer fetched successfully');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      logger.error('[DealerController] Error fetching dealer by email:', error);
      return ResponseHandler.error(res, 'Failed to fetch dealer', 500, errorMessage);
    }
  }

  /**
   * Search dealers
   * GET /api/v1/dealers/search?q=searchTerm&limit=10
   */
  async searchDealers(req: Request, res: Response): Promise<void> {
    try {
      const { q, limit: limitParam } = req.query;
      
      if (!q || typeof q !== 'string') {
        return ResponseHandler.error(res, 'Search term is required', 400);
      }

      // Parse limit, default to 10, max 100
      const limit = limitParam ? Math.min(Math.max(1, parseInt(limitParam as string, 10)), 100) : 10;
      const dealers = await dealerService.searchDealers(q, limit);
      return ResponseHandler.success(res, dealers, 'Dealers searched successfully');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      logger.error('[DealerController] Error searching dealers:', error);
      return ResponseHandler.error(res, 'Failed to search dealers', 500, errorMessage);
    }
  }

  /**
   * Verify dealer is logged in
   * GET /api/v1/dealers/verify/:dealerCode
   * Returns dealer info with isLoggedIn flag
   */
  async verifyDealerLogin(req: Request, res: Response): Promise<void> {
    try {
      const { dealerCode } = req.params;
      const dealer = await dealerService.getDealerByCode(dealerCode);

      if (!dealer) {
        return ResponseHandler.error(res, 'Dealer not found', 404);
      }

      if (!dealer.isLoggedIn) {
        return ResponseHandler.error(
          res,
          'Dealer not logged in to the system',
          400,
          `The dealer with code ${dealerCode} (${dealer.email}) has not logged in to the system. Please ask them to log in first.`
        );
      }

      return ResponseHandler.success(res, dealer, 'Dealer verified and logged in');
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';
      logger.error('[DealerController] Error verifying dealer login:', error);
      return ResponseHandler.error(res, 'Failed to verify dealer', 500, errorMessage);
    }
  }
}

