const TravelService = require('../../services/travel');
const { success } = require('../../utils/response');
const { AppError } = require('../../utils/errors');

class TravelController {
  // 获取旅行计划列表
  static async getTravelPlans(req, res, next) {
    try {
      const { page, pageSize, status } = req.query;
      
      const result = await TravelService.getTravelPlans({
        userId: req.userId,
        page: parseInt(page) || 1,
        pageSize: parseInt(pageSize) || 10,
        status
      });

      res.json(success(result));
    } catch (error) {
      next(error);
    }
  }

  // 获取单个旅行计划详情
  static async getTravelPlan(req, res, next) {
    try {
      const { planId } = req.params;
      
      if (!planId) {
        throw new AppError('旅行计划ID不能为空', 400);
      }

      const plan = await TravelService.getTravelPlanById(planId);
      res.json(success({ plan }));
    } catch (error) {
      next(error);
    }
  }

  // 创建旅行计划
  static async createTravelPlan(req, res, next) {
    try {
      const {
        title,
        description,
        destination,
        start_date,
        end_date,
        max_participants,
        price_per_person,
        itinerary,
        requirements,
        includes,
        excludes,
        images
      } = req.body;

      if (!title || !destination || !start_date || !end_date || !price_per_person) {
        throw new AppError('标题、目的地、开始日期、结束日期和价格不能为空', 400);
      }

      const planData = {
        title,
        description: description || null,
        destination,
        start_date,
        end_date,
        max_participants: max_participants || null,
        price_per_person: parseFloat(price_per_person),
        itinerary: itinerary || [],
        requirements: requirements || null,
        includes: includes || [],
        excludes: excludes || [],
        images: images || []
      };

      // 调试：检查传递给服务层的数据
      console.log('Plan Data:', planData);
      Object.keys(planData).forEach(key => {
        if (planData[key] === undefined) {
          console.log(`Field ${key} is undefined`);
        }
      });

      const planId = await TravelService.createTravelPlan(req.userId, planData);

      const plan = await TravelService.getTravelPlanById(planId);

      res.status(201).json(success({
        plan,
        message: '旅行计划创建成功'
      }));
    } catch (error) {
      next(error);
    }
  }

  // 更新旅行计划
  static async updateTravelPlan(req, res, next) {
    try {
      const { planId } = req.params;
      
      if (!planId) {
        throw new AppError('旅行计划ID不能为空', 400);
      }

      const plan = await TravelService.updateTravelPlan(planId, req.userId, req.body);
      
      res.json(success({
        plan,
        message: '旅行计划更新成功'
      }));
    } catch (error) {
      next(error);
    }
  }

  // 删除旅行计划
  static async deleteTravelPlan(req, res, next) {
    try {
      const { planId } = req.params;
      
      if (!planId) {
        throw new AppError('旅行计划ID不能为空', 400);
      }

      await TravelService.deleteTravelPlan(planId, req.userId);
      
      res.json(success({
        message: '旅行计划删除成功',
        planId: parseInt(planId)
      }));
    } catch (error) {
      next(error);
    }
  }

  // 获取用户旅行统计
  static async getTravelStats(req, res, next) {
    try {
      const stats = await TravelService.getUserTravelStats(req.userId);
      
      res.json(success({ stats }));
    } catch (error) {
      next(error);
    }
  }

  // 获取所有旅行计划（管理员功能）
  static async getAllTravelPlans(req, res, next) {
    try {
      const { page, pageSize, status, userId } = req.query;
      
      const result = await TravelService.getTravelPlans({
        userId,
        page: parseInt(page) || 1,
        pageSize: parseInt(pageSize) || 10,
        status
      });

      res.json(success(result));
    } catch (error) {
      next(error);
    }
  }
}

module.exports = TravelController;