/**
 * 图文任务服务模块
 * 负责任务详情和进度相关的 API 调用
 */

import { campApi } from '../../../config/camp_api.js';

/**
 * 获取任务详情
 * @param {String} taskId - 任务ID
 * @returns {Promise} 任务详情
 */
export function getTaskDetail(taskId) {
	if (!taskId) {
		return Promise.reject(new Error('任务ID为空'));
	}

	return campApi.getTaskDetailById(taskId).then(res => {
		if (res && res.success === true && res.task) {
			const task = res.task || {};
			const content = task.content || {};
			const condition = task.condition || {};
			// 数据嵌套在 image_text 子对象中
			const imageTextContent = content.image_text || {};
			const imageTextCondition = condition.image_text || {};
			const imageUrlRaw = imageTextContent.image_url || '';
			const textContent = imageTextContent.text_content || '';
			const durationSeconds = imageTextCondition.view_duration_seconds || 0;
			
			const imageUrl = (imageUrlRaw && /^https?:\/\//.test(imageUrlRaw)) 
				? imageUrlRaw 
				: (imageUrlRaw ? ('https://' + imageUrlRaw) : '');
			
			const validDuration = Number(durationSeconds) || 0;
			
			return {
				imageUrl,
				textContent,
				taskType: task.task_type || 'TASK_TYPE_IMAGE_TEXT',
				remainingTime: validDuration
			};
		} else {
			throw new Error('任务详情接口返回格式不符合预期');
		}
	});
}

/**
 * 获取任务进度
 * @param {String} userId - 用户ID
 * @param {String} taskId - 任务ID
 * @returns {Promise} 任务进度
 */
export function getProgressDetail(userId, taskId) {
	if (!userId || !taskId) {
		return Promise.resolve(null);
	}

	return campApi.getProgressDetail(userId, taskId).then(res => {
		if (res && res.success === true && res.progress) {
			return res.progress;
		}
		return null;
	}).catch(err => {
		console.error('获取任务进度失败:', err);
		return null;
	});
}

/**
 * 更新任务进度为已完成
 * @param {String} userId - 用户ID
 * @param {String} taskId - 任务ID
 * @returns {Promise} 更新结果
 */
export function updateProgressToCompleted(userId, taskId) {
	const completedAt = Math.floor(Date.now() / 1000);
	
	return campApi.updateCampProgress({
		user_id: String(userId),
		task_id: String(taskId),
		is_completed: true,
		completed_at: String(completedAt),
		review_status: 'pending',
		review_comment: '',
		review_images: []
	});
}

