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

export class HsnSacCodeController {
  /**
   * Get HSN/SAC codes with pagination and search
   */
  async getAllCodes(req: Request, res: Response): Promise<void> {
    try {
      const onlyActive = req.query.active === 'true';
      const page = parseInt(req.query.page as string) || 1;
      const limit = parseInt(req.query.limit as string) || 10;
      const search = req.query.search as string;

      const result = await hsnSacCodeService.getAllCodes(onlyActive, page, limit, search);
      
      ResponseHandler.success(
        res, 
        result.codes, 
        'HSN/SAC codes fetched successfully', 
        200, 
        result.pagination
      );
    } catch (error: any) {
      logger.error('Error in getAllCodes controller:', error);
      ResponseHandler.error(res, 'Failed to fetch HSN/SAC codes', 500, error.message);
    }
  }

  /**
   * Get code by ID
   */
  async getCodeById(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const code = await hsnSacCodeService.getCodeById(id);
      if (!code) {
        return ResponseHandler.error(res, 'HSN/SAC code not found', 404);
      }
      ResponseHandler.success(res, code, 'HSN/SAC code fetched successfully');
    } catch (error: any) {
      logger.error('Error in getCodeById controller:', error);
      ResponseHandler.error(res, 'Failed to fetch HSN/SAC code', 500, error.message);
    }
  }

  /**
   * Create new code
   */
  async createCode(req: Request, res: Response): Promise<void> {
    try {
      const { code, type, gstRate, description, isActive } = req.body;
      
      if (!code || !type) {
        return ResponseHandler.error(res, 'Code and type are required', 400);
      }

      const newCode = await hsnSacCodeService.createCode({
        code,
        type,
        gstRate,
        description,
        isActive: isActive !== undefined ? isActive : true
      });

      ResponseHandler.success(res, newCode, 'HSN/SAC code created successfully', 201);
    } catch (error: any) {
      logger.error('Error in createCode controller:', error);
      ResponseHandler.error(res, 'Failed to create HSN/SAC code', 500, error.message);
    }
  }

  /**
   * Update code
   */
  async updateCode(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const updatedCode = await hsnSacCodeService.updateCode(id, req.body);
      
      if (!updatedCode) {
        return ResponseHandler.error(res, 'HSN/SAC code not found', 404);
      }

      ResponseHandler.success(res, updatedCode, 'HSN/SAC code updated successfully');
    } catch (error: any) {
      logger.error('Error in updateCode controller:', error);
      ResponseHandler.error(res, 'Failed to update HSN/SAC code', 500, error.message);
    }
  }

  /**
   * Delete code
   */
  async deleteCode(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const success = await hsnSacCodeService.deleteCode(id);
      
      if (!success) {
        return ResponseHandler.error(res, 'HSN/SAC code not found', 404);
      }

      ResponseHandler.success(res, null, 'HSN/SAC code deleted successfully');
    } catch (error: any) {
      logger.error('Error in deleteCode controller:', error);
      ResponseHandler.error(res, 'Failed to delete HSN/SAC code', 500, error.message);
    }
  }

  /**
   * Toggle active status
   */
  async toggleActive(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const updatedCode = await hsnSacCodeService.toggleActive(id);
      
      if (!updatedCode) {
        return ResponseHandler.error(res, 'HSN/SAC code not found', 404);
      }

      ResponseHandler.success(res, updatedCode, 'HSN/SAC code status toggled successfully');
    } catch (error: any) {
      logger.error('Error in toggleActive controller:', error);
      ResponseHandler.error(res, 'Failed to toggle HSN/SAC code status', 500, error.message);
    }
  }
}

export const hsnSacCodeController = new HsnSacCodeController();
