//
//  WeChatShareServiceTests.swift
//  suixinkanTests
//

import UIKit
import XCTest
@testable import suixinkan

/// 微信分享服务测试。
@MainActor
final class WeChatShareServiceTests: XCTestCase {
    /// 测试 Universal Link 必须是 HTTPS 且以 `/` 结尾。
    func testUniversalLinkMustUseHTTPSAndEndWithSlash() {
        XCTAssertTrue(WeChatConfig.validateUniversalLink(WeChatConfig.universalLink))
        XCTAssertFalse(WeChatConfig.validateUniversalLink("https://www.zhifly.cn/suixinkan"))
        XCTAssertFalse(WeChatConfig.validateUniversalLink("http://www.zhifly.cn/suixinkan/"))
    }

    /// 测试分享场景映射到微信 SDK scene 值。
    func testShareSceneMapsToWXValues() {
        XCTAssertEqual(WeChatShareScene.session.wxSceneValue, 0)
        XCTAssertEqual(WeChatShareScene.timeline.wxSceneValue, 1)
        XCTAssertEqual(WeChatShareScene.favorite.wxSceneValue, 2)
    }

    /// 测试微信错误码解析。
    func testShareResultFromWXErrorCode() {
        XCTAssertEqual(WeChatShareResult.fromWXErrorCode(0), .success)
        XCTAssertEqual(WeChatShareResult.fromWXErrorCode(-2), .cancelled)
        XCTAssertEqual(WeChatShareResult.fromWXErrorCode(99), .unknown(99))
    }

    /// 测试缩略图压缩到微信限制内。
    func testThumbImageProcessorKeepsDataUnderLimit() throws {
        let renderer = UIGraphicsImageRenderer(size: CGSize(width: 640, height: 640))
        let image = renderer.image { context in
            UIColor.systemBlue.setFill()
            context.fill(CGRect(x: 0, y: 0, width: 640, height: 640))
            UIColor.white.setFill()
            context.fill(CGRect(x: 80, y: 80, width: 480, height: 480))
        }

        let thumbData = try XCTUnwrap(WeChatThumbImageProcessor.makeThumbData(from: image))
        XCTAssertLessThanOrEqual(thumbData.count, WeChatThumbImageProcessor.maxThumbBytes)
    }

    /// 测试空标题和空链接会直接返回参数错误。
    func testShareWebPageRejectsInvalidPayloadBeforeSending() {
        var results: [WeChatShareResult] = []
        WeChatShareService.shareWebPage(
            WeChatWebPageSharePayload(title: " ", description: "desc", url: "https://example.com"),
            scene: .session
        ) { result in
            results.append(result)
        }
        WeChatShareService.shareWebPage(
            WeChatWebPageSharePayload(title: "title", description: "desc", url: " "),
            scene: .session
        ) { result in
            results.append(result)
        }

        XCTAssertEqual(results, [
            .invalidPayload("分享标题不能为空"),
            .invalidPayload("分享链接不能为空"),
        ])
    }
}
