import { ApiResponse } from '@goodgo/types';
import { Request, Response } from 'express';

import { asyncHandler } from '../../middlewares/error.middleware';

import { FeatureService } from './feature.service';


/**
 * EN: Controller for Feature module
 * VI: Controller cho module Feature
 */
export class FeatureController {
  private featureService: FeatureService;

  constructor() {
    // EN: Service initialization
    // VI: Khởi tạo service
    this.featureService = new FeatureService();
  }

  /**
   * EN: Create a new feature
   * VI: Tạo một feature mới
   *
   * @param req - Express request
   * @param res - Express response
   */
  create = asyncHandler(async (req: Request, res: Response): Promise<void> => {
    const featureData = req.body;
    const feature = await this.featureService.create(featureData);

    const response: ApiResponse = {
      success: true,
      data: feature,
      message: 'Feature created successfully / Feature đã được tạo thành công',
      timestamp: new Date().toISOString(),
    };
    res.status(201).json(response);
  });

  /**
   * EN: Get all features
   * VI: Lấy tất cả features
   */
  getAll = asyncHandler(async (_req: Request, res: Response): Promise<void> => {
    const features = await this.featureService.findAll();

    const response: ApiResponse = {
      success: true,
      data: features,
      message: 'Features retrieved successfully / Features đã được lấy thành công',
      timestamp: new Date().toISOString(),
    };
    res.json(response);
  });

  /**
   * EN: Get feature by ID
   * VI: Lấy feature theo ID
   */
  getById = async (req: Request, res: Response): Promise<void> => {
    try {
      const { id } = req.params;
      const feature = await this.featureService.findById(id);

      if (!feature) {
        res.status(404).json({
          success: false,
          error: {
            code: 'FEATURE_003',
            message: 'Feature not found / Không tìm thấy feature',
          },
          timestamp: new Date().toISOString(),
        });
        return;
      }

      const response: ApiResponse = {
        success: true,
        data: feature,
        message: 'Feature retrieved successfully / Feature đã được lấy thành công',
        timestamp: new Date().toISOString(),
      };
      res.json(response);
    } catch (error: any) {
      res.status(500).json({
        success: false,
        error: {
          code: 'FEATURE_004',
          message: error.message || 'Failed to retrieve feature / Không thể lấy feature',
        },
        timestamp: new Date().toISOString(),
      });
    }
  };

  /**
   * EN: Update feature
   * VI: Cập nhật feature
   */
  update = async (req: Request, res: Response): Promise<void> => {
    try {
      const { id } = req.params;
      const updateData = req.body;
      const feature = await this.featureService.update(id, updateData);

      const response: ApiResponse = {
        success: true,
        data: feature,
        message: 'Feature updated successfully / Feature đã được cập nhật thành công',
        timestamp: new Date().toISOString(),
      };
      res.json(response);
    } catch (error: any) {
      res.status(400).json({
        success: false,
        error: {
          code: 'FEATURE_005',
          message: error.message || 'Failed to update feature / Không thể cập nhật feature',
        },
        timestamp: new Date().toISOString(),
      });
    }
  };

  /**
   * EN: Delete feature
   * VI: Xóa feature
   */
  delete = async (req: Request, res: Response): Promise<void> => {
    try {
      const { id } = req.params;
      await this.featureService.delete(id);

      const response: ApiResponse = {
        success: true,
        message: 'Feature deleted successfully / Feature đã được xóa thành công',
        timestamp: new Date().toISOString(),
      };
      res.json(response);
    } catch (error: any) {
      res.status(400).json({
        success: false,
        error: {
          code: 'FEATURE_006',
          message: error.message || 'Failed to delete feature / Không thể xóa feature',
        },
        timestamp: new Date().toISOString(),
      });
    }
  };

  /**
   * EN: Toggle feature status
   * VI: Chuyển đổi trạng thái feature
   */
  toggle = async (req: Request, res: Response): Promise<void> => {
    try {
      const { id } = req.params;
      const feature = await this.featureService.toggle(id);

      const response: ApiResponse = {
        success: true,
        data: feature,
        message: `Feature ${feature.enabled ? 'enabled' : 'disabled'} successfully / Feature đã được ${feature.enabled ? 'bật' : 'tắt'} thành công`,
        timestamp: new Date().toISOString(),
      };
      res.json(response);
    } catch (error: any) {
      res.status(400).json({
        success: false,
        error: {
          code: 'FEATURE_007',
          message: error.message || 'Failed to toggle feature / Không thể chuyển đổi feature',
        },
        timestamp: new Date().toISOString(),
      });
    }
  };
}
