package com.dora.service;

import com.dora.config.CosConfig;
import com.dora.util.OssUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.model.GeneratePresignedUrlRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 腾讯云COS服务类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OssService {

    private final COSClient cosClient;
    private final CosConfig cosConfig;

    /**
     * 生成预签名上传URL
     *
     * @param fileName 文件名
     * @param userId   用户ID
     * @return 预签名URL信息
     */
    public Map<String, Object> generatePresignedUploadUrl(String fileName, String userId) {
        try {
            // 验证文件类型
            if (!OssUtil.isAllowedFileType(fileName)) {
                throw new IllegalArgumentException("不支持的文件类型，支持格式：图片(jpg,jpeg,png,gif,bmp,webp)、压缩包(zip,rar,7z,tar,gz,bz2,xz)、文档(pdf,txt,md,json,xml,csv)");
            }
            
            // 生成唯一的文件名
            String uniqueFileName = OssUtil.generateUniqueFileName(fileName, Long.valueOf(userId));
            String objectKey = cosConfig.getUserImgFolder() + "/" + uniqueFileName;

            // 获取文件类型
            String contentType = OssUtil.getContentType(fileName);

            // 设置请求头 - 简化版本，不包含回调
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", contentType);

            // 设置过期时间
            Date expiration = new Date(System.currentTimeMillis() + cosConfig.getExpirationSeconds() * 1000);

            // 构造 COS 预签名请求（PUT 上传）
            GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(cosConfig.getBucketName(), objectKey, HttpMethodName.PUT);
            request.setExpiration(expiration);

            // 生成预签名URL
            URL url = cosClient.generatePresignedUrl(request);

            // 格式化过期时间
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            String expirationStr = dateFormat.format(expiration);

            // 返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("method", "PUT");
            result.put("expiration", expirationStr);
            result.put("url", url.toString());
            result.put("objectKey", objectKey);
            result.put("fileName", fileName);
            result.put("userId", userId);
            result.put("contentType", contentType);
            
            // 返回必需的请求头信息
            Map<String, String> requiredHeaders = new HashMap<>();
            requiredHeaders.put("Content-Type", contentType);
            result.put("headers", requiredHeaders);

            log.info("Generated presigned URL for user {}: {}", userId, objectKey);
            return result;

        } catch (Exception e) {
            log.error("Failed to generate presigned URL for user {}: {}", userId, e.getMessage(), e);
            throw new RuntimeException("Failed to generate presigned URL", e);
        }
    }

    /**
     * 处理COS回调
     *
     * @param callbackData 回调数据
     * @return 处理结果
     */
    public Map<String, Object> handleCallback(Map<String, String> callbackData) {
        try {
            String bucket = callbackData.get("bucket");
            String object = callbackData.get("object");
            String userId = callbackData.get("userId");
            String fileName = callbackData.get("fileName");

            log.info("Received COS callback - bucket: {}, object: {}, userId: {}, fileName: {}", 
                    bucket, object, userId, fileName);

            // 这里可以添加业务逻辑，比如：
            // 1. 更新用户头像信息到数据库
            // 2. 发送通知
            // 3. 记录上传日志等

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "File uploaded successfully");
            result.put("bucket", bucket);
            result.put("object", object);
            result.put("userId", userId);
            result.put("fileName", fileName);
            result.put("uploadTime", new Date());

            return result;

        } catch (Exception e) {
            log.error("Failed to handle COS callback: {}", e.getMessage(), e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "Failed to handle callback: " + e.getMessage());
            return result;
        }
    }

    /**
     * 删除COS文件
     *
     * @param objectKey 对象键
     * @return 是否删除成功
     */
    public boolean deleteFile(String objectKey) {
        try {
            cosClient.deleteObject(cosConfig.getBucketName(), objectKey);
            log.info("Deleted COS file: {}", objectKey);
            return true;
        } catch (Exception e) {
            log.error("Failed to delete COS file {}: {}", objectKey, e.getMessage(), e);
            return false;
        }
    }
} 