#import "TQDownloadResponseHandler.h"
#import "TQHTTPHeaderCompat.h"

@implementation TQDownloadResponseHandler

/// 命中以下 MIME 类型时,即使服务器未返回 Content-Disposition: attachment,
/// 也视为下载候选(这些类型在移动端没有"在线编辑"场景,用户点击即期望下载)。
+ (NSSet<NSString *> *)downloadableMimeTypes {
    static NSSet *set;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        set = [NSSet setWithArray:@[
            // PDF
            @"application/pdf",
            // Microsoft Office (OpenXML)
            @"application/vnd.openxmlformats-officedocument.wordprocessingml.document",   // .docx
            @"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",          // .xlsx
            @"application/vnd.openxmlformats-officedocument.presentationml.presentation",  // .pptx
            // Microsoft Office (Legacy)
            @"application/msword",            // .doc
            @"application/vnd.ms-excel",      // .xls
            @"application/vnd.ms-powerpoint", // .ppt
            // WPS Office
            @"application/vnd.ms-works",      // .wps
            // CSV(text 类型,WKWebView 可能尝试渲染而非下载,必须显式声明)
            @"text/csv",                      // .csv
            // OFD(中国电子文档标准,电子签场景常见)
            @"application/ofd",               // .ofd
            // 压缩包
            @"application/zip",
            @"application/x-zip-compressed",
            @"application/x-7z-compressed",   // .7z
            @"application/x-rar-compressed",  // .rar (传统)
            @"application/vnd.rar",           // .rar (IANA 标准)
            @"application/gzip",              // .gz
            // 通用二进制流(服务器未正确配置 MIME 时常见)
            @"application/octet-stream",
        ]];
    });
    return set;
}

+ (TQDownloadDecision)decideForResponse:(WKNavigationResponse *)navigationResponse
                                onEvent:(TQOnEventBlock)onEvent {
    NSURLResponse *urlResponse = navigationResponse.response;
    BOOL canShow = navigationResponse.canShowMIMEType;
    BOOL isDownloadCandidate = [self isDownloadable:urlResponse] || !canShow;
    if (!isDownloadCandidate) return TQDownloadDecisionAllow;
    // 统一返回 Download,由 TQNavigationDelegate 调用 TQDownloadManager 处理
    return TQDownloadDecisionDownload;
}

+ (BOOL)isDownloadable:(NSURLResponse *)response {
    NSString *mime = [(response.MIMEType ?: @"") lowercaseString];
    if ([[self downloadableMimeTypes] containsObject:mime]) return YES;
    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *http = (NSHTTPURLResponse *)response;
        NSString *disposition = [TQHTTPHeaderCompat valueForHeaderField:@"Content-Disposition" inResponse:response];
        if ([[disposition lowercaseString] containsString:@"attachment"]) return YES;
    }
    return NO;
}

@end
