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

import UIKit
import XCTest
@testable import suixinkan

final class WeChatShareServiceTests: XCTestCase {
    func testUniversalLinkMustEndWithSlash() {
        XCTAssertTrue(WeChatConfig.validateUniversalLink(WeChatConfig.universalLink))
        XCTAssertFalse(WeChatConfig.validateUniversalLink("https://www.zhifly.cn/suixinkan"))
        XCTAssertFalse(WeChatConfig.validateUniversalLink("http://www.zhifly.cn/suixinkan/"))
    }

    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 testThumbImageCompressionStaysWithinLimit() throws {
        let size = CGSize(width: 512, height: 512)
        let format = UIGraphicsImageRendererFormat.default()
        format.scale = 1
        let renderer = UIGraphicsImageRenderer(size: size, format: format)
        let image = renderer.image { context in
            UIColor.systemBlue.setFill()
            context.fill(CGRect(origin: .zero, size: size))
        }

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

    func testThumbImageResizeReducesLargeImage() {
        let size = CGSize(width: 800, height: 600)
        let format = UIGraphicsImageRendererFormat.default()
        format.scale = 1
        let renderer = UIGraphicsImageRenderer(size: size, format: format)
        let image = renderer.image { _ in }

        let resized = WeChatThumbImageProcessor.resize(image, maxPixel: 120)
        XCTAssertLessThanOrEqual(max(resized.size.width, resized.size.height), 120)
    }

    func testWebPagePayloadValidationRequiresNonEmptyFields() async {
        await MainActor.run {
            let expectation = expectation(description: "invalid title")
            WeChatShareService.shareWebPage(
                WeChatWebPageSharePayload(title: " ", description: "desc", url: "https://example.com"),
                scene: .session
            ) { result in
                if case .invalidPayload = result {
                    expectation.fulfill()
                }
            }
            wait(for: [expectation], timeout: 1)
        }
    }
}
