const { query } = require('../config/database');
const { AppError } = require('../utils/errors');

/**
 * 旅行活动报名服务
 */
class TravelRegistrationService {
  /**
   * 用户报名参加旅行活动
   */
  static async registerForTravel(registrationData) {
    try {
      const { userId, travelId, message, emergencyContact, emergencyPhone } = registrationData;

      // 检查旅行活动是否存在且可报名
      const travelSql = `
        SELECT tp.*, u.username as organizer_name
        FROM travel_plans tp
        INNER JOIN users u ON tp.user_id = u.id
        WHERE tp.id = ? AND tp.status = 'active'
      `;
      const travels = await query(travelSql, [travelId]);
      
      if (travels.length === 0) {
        throw new AppError('旅行活动不存在或已关闭', 404);
      }

      const travel = travels[0];

      // 检查是否为活动发起者
      if (travel.user_id === userId) {
        throw new AppError('不能报名自己发起的活动', 400);
      }

      // 检查是否已经报名
      const existingSql = 'SELECT id FROM travel_matches WHERE travel_plan_id = ? AND user_id = ?';
      const existing = await query(existingSql, [travelId, userId]);
      
      if (existing.length > 0) {
        throw new AppError('您已经报名过此活动', 400);
      }

      // 检查活动是否已满员
      if (travel.current_participants >= travel.max_participants) {
        throw new AppError('活动已满员', 400);
      }

      // 创建报名记录
      const insertSql = `
        INSERT INTO travel_matches (
          travel_plan_id, user_id, message, emergency_contact, emergency_phone,
          status, applied_at, created_at, updated_at
        ) VALUES (?, ?, ?, ?, ?, 'pending', NOW(), NOW(), NOW())
      `;

      const result = await query(insertSql, [
        travelId, userId, message, emergencyContact, emergencyPhone
      ]);

      // 获取完整的报名信息
      const registrationSql = `
        SELECT tm.*, u.username, u.real_name, u.avatar_url, u.phone
        FROM travel_matches tm
        INNER JOIN users u ON tm.user_id = u.id
        WHERE tm.id = ?
      `;
      const registrations = await query(registrationSql, [result.insertId]);

      return this.sanitizeRegistration(registrations[0]);
    } catch (error) {
      throw error;
    }
  }

  /**
   * 取消报名
   */
  static async cancelRegistration(registrationId, userId) {
    try {
      // 检查报名记录是否存在且属于当前用户
      const checkSql = `
        SELECT tm.*, tp.status as travel_status
        FROM travel_matches tm
        INNER JOIN travel_plans tp ON tm.travel_plan_id = tp.id
        WHERE tm.id = ? AND tm.user_id = ?
      `;
      const registrations = await query(checkSql, [registrationId, userId]);

      if (registrations.length === 0) {
        throw new AppError('报名记录不存在', 404);
      }

      const registration = registrations[0];

      // 检查是否可以取消
      if (registration.status === 'cancelled') {
        throw new AppError('报名已取消', 400);
      }

      if (registration.travel_status === 'completed') {
        throw new AppError('活动已结束，无法取消报名', 400);
      }

      // 更新报名状态
      const updateSql = `
        UPDATE travel_matches 
        SET status = 'cancelled', updated_at = NOW()
        WHERE id = ?
      `;
      await query(updateSql, [registrationId]);

      // 如果之前是已通过状态，需要减少活动参与人数
      if (registration.status === 'approved') {
        const decreaseSql = `
          UPDATE travel_plans 
          SET current_participants = current_participants - 1,
              updated_at = NOW()
          WHERE id = ?
        `;
        await query(decreaseSql, [registration.travel_plan_id]);
      }

      return true;
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取用户的报名记录
   */
  static async getUserRegistrations(searchParams) {
    try {
      const { userId, page = 1, pageSize = 10, status } = searchParams;
      const offset = (page - 1) * pageSize;

      let sql = `
        SELECT tm.*, tp.destination, tp.start_date, tp.end_date, tp.budget,
               tp.title, tp.status as travel_status, u.username as organizer_name
        FROM travel_matches tm
        INNER JOIN travel_plans tp ON tm.travel_plan_id = tp.id
        INNER JOIN users u ON tp.user_id = u.id
        WHERE tm.user_id = ?
      `;
      const params = [userId];

      if (status) {
        sql += ' AND tm.status = ?';
        params.push(status);
      }

      // 获取总数
      const countSql = `SELECT COUNT(*) as total FROM (${sql}) as count_query`;
      const countResult = await query(countSql, params);
      const total = countResult[0].total;

      // 添加分页和排序
      sql += ' ORDER BY tm.applied_at DESC LIMIT ? OFFSET ?';
      params.push(pageSize, offset);

      const registrations = await query(sql, params);

      return {
        registrations: registrations.map(reg => this.sanitizeRegistration(reg)),
        pagination: {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          total: parseInt(total),
          totalPages: Math.ceil(total / pageSize)
        }
      };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取旅行活动的报名列表
   */
  static async getTravelRegistrations(searchParams) {
    try {
      const { travelId, organizerId, page = 1, pageSize = 10, status } = searchParams;
      const offset = (page - 1) * pageSize;

      // 验证活动发起者权限
      const travelSql = 'SELECT user_id FROM travel_plans WHERE id = ?';
      const travels = await query(travelSql, [travelId]);
      
      if (travels.length === 0) {
        throw new AppError('旅行活动不存在', 404);
      }

      if (travels[0].user_id !== organizerId) {
        throw new AppError('无权查看此活动的报名信息', 403);
      }

      let sql = `
        SELECT tm.*, u.username, u.real_name, u.avatar_url, u.phone, u.gender, u.age
        FROM travel_matches tm
        INNER JOIN users u ON tm.user_id = u.id
        WHERE tm.travel_plan_id = ?
      `;
      const params = [travelId];

      if (status) {
        sql += ' AND tm.status = ?';
        params.push(status);
      }

      // 获取总数
      const countSql = `SELECT COUNT(*) as total FROM (${sql}) as count_query`;
      const countResult = await query(countSql, params);
      const total = countResult[0].total;

      // 添加分页和排序
      sql += ' ORDER BY tm.applied_at DESC LIMIT ? OFFSET ?';
      params.push(pageSize, offset);

      const registrations = await query(sql, params);

      return {
        registrations: registrations.map(reg => this.sanitizeRegistration(reg)),
        pagination: {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          total: parseInt(total),
          totalPages: Math.ceil(total / pageSize)
        }
      };
    } catch (error) {
      throw error;
    }
  }

  /**
   * 审核报名申请
   */
  static async reviewRegistration(reviewData) {
    try {
      const { registrationId, organizerId, action, rejectReason } = reviewData;

      // 检查报名记录和权限
      const checkSql = `
        SELECT tm.*, tp.user_id as organizer_id, tp.max_participants, tp.current_participants
        FROM travel_matches tm
        INNER JOIN travel_plans tp ON tm.travel_plan_id = tp.id
        WHERE tm.id = ?
      `;
      const registrations = await query(checkSql, [registrationId]);

      if (registrations.length === 0) {
        throw new AppError('报名记录不存在', 404);
      }

      const registration = registrations[0];

      if (registration.organizer_id !== organizerId) {
        throw new AppError('无权操作此报名记录', 403);
      }

      if (registration.status !== 'pending') {
        throw new AppError('此报名已处理过', 400);
      }

      // 如果是通过申请，检查是否还有名额
      if (action === 'approve' && registration.current_participants >= registration.max_participants) {
        throw new AppError('活动已满员，无法通过更多申请', 400);
      }

      // 更新报名状态
      const updateSql = `
        UPDATE travel_matches 
        SET status = ?, reject_reason = ?, responded_at = NOW(), updated_at = NOW()
        WHERE id = ?
      `;
      const newStatus = action === 'approve' ? 'approved' : 'rejected';
      await query(updateSql, [newStatus, rejectReason || null, registrationId]);

      // 如果通过申请，增加活动参与人数
      if (action === 'approve') {
        const increaseSql = `
          UPDATE travel_plans 
          SET current_participants = current_participants + 1,
              updated_at = NOW()
          WHERE id = ?
        `;
        await query(increaseSql, [registration.travel_plan_id]);
      }

      // 返回更新后的报名信息
      const resultSql = `
        SELECT tm.*, u.username, u.real_name, u.avatar_url
        FROM travel_matches tm
        INNER JOIN users u ON tm.user_id = u.id
        WHERE tm.id = ?
      `;
      const results = await query(resultSql, [registrationId]);

      return this.sanitizeRegistration(results[0]);
    } catch (error) {
      throw error;
    }
  }

  /**
   * 获取报名统计信息
   */
  static async getRegistrationStats(travelId, organizerId) {
    try {
      // 验证权限
      const travelSql = 'SELECT user_id FROM travel_plans WHERE id = ?';
      const travels = await query(travelSql, [travelId]);
      
      if (travels.length === 0) {
        throw new AppError('旅行活动不存在', 404);
      }

      if (travels[0].user_id !== organizerId) {
        throw new AppError('无权查看此活动的统计信息', 403);
      }

      // 获取统计数据
      const statsSql = `
        SELECT 
          COUNT(*) as total_applications,
          COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count,
          COUNT(CASE WHEN status = 'approved' THEN 1 END) as approved_count,
          COUNT(CASE WHEN status = 'rejected' THEN 1 END) as rejected_count,
          COUNT(CASE WHEN status = 'cancelled' THEN 1 END) as cancelled_count
        FROM travel_matches 
        WHERE travel_plan_id = ?
      `;

      const stats = await query(statsSql, [travelId]);
      return stats[0];
    } catch (error) {
      throw error;
    }
  }

  /**
   * 清理报名信息，移除敏感数据
   */
  static sanitizeRegistration(registration) {
    if (!registration) return null;

    const sanitized = { ...registration };
    
    // 移除敏感信息
    delete sanitized.emergency_phone;
    
    return sanitized;
  }
}

module.exports = TravelRegistrationService;