//
//  MediaPreviewModelsTests.swift
//  suixinkanTests
//

import UIKit
import XCTest
@testable import suixinkan

/// 通用媒体预览模型测试。
final class MediaPreviewModelsTests: XCTestCase {

    func testClampedStartIndexKeepsIndexInBounds() {
        XCTAssertEqual(MediaPreviewItem.clampedStartIndex(-3, itemCount: 4), 0)
        XCTAssertEqual(MediaPreviewItem.clampedStartIndex(2, itemCount: 4), 2)
        XCTAssertEqual(MediaPreviewItem.clampedStartIndex(8, itemCount: 4), 3)
        XCTAssertEqual(MediaPreviewItem.clampedStartIndex(8, itemCount: 0), 0)
    }

    func testRemoteImageAndVideoURLConstructionFiltersInvalidText() {
        let image = MediaPreviewItem.remoteImage(" https://cdn.example.com/a.jpg ")
        let video = MediaPreviewItem.remoteVideo("https://cdn.example.com/a.mp4")

        XCTAssertEqual(image?.mediaType, .image)
        XCTAssertEqual(video?.mediaType, .video)
        XCTAssertNil(MediaPreviewItem.remoteImage(""))
        XCTAssertNil(MediaPreviewItem.remoteImage("   "))
        XCTAssertNil(MediaPreviewItem.remoteVideo("file:///tmp/a.mp4"))
        XCTAssertNil(MediaPreviewItem.remoteVideo("not a url"))
    }

    func testLocalImageAndVideoTypeRecognition() {
        let localImage = MediaPreviewItem.localImage(url: URL(fileURLWithPath: "/tmp/a.jpg"))
        let memoryImage = MediaPreviewItem.image(UIImage())
        let localVideo = MediaPreviewItem.localVideo(url: URL(fileURLWithPath: "/tmp/a.mp4"))

        XCTAssertTrue(localImage.isImage)
        XCTAssertTrue(memoryImage.isImage)
        XCTAssertTrue(localVideo.isVideo)
        XCTAssertEqual(localVideo.mediaType, .video)
    }

    func testCurrentItemReadsClampedItemFromMixedMedia() {
        let items = [
            MediaPreviewItem.localImage(url: URL(fileURLWithPath: "/tmp/a.jpg")),
            MediaPreviewItem.localVideo(url: URL(fileURLWithPath: "/tmp/a.mp4")),
            MediaPreviewItem.remoteImage("https://cdn.example.com/b.jpg")!,
        ]

        XCTAssertEqual(MediaPreviewItem.currentItem(in: items, startIndex: -1)?.mediaType, .image)
        XCTAssertEqual(MediaPreviewItem.currentItem(in: items, startIndex: 1)?.mediaType, .video)
        XCTAssertEqual(MediaPreviewItem.currentItem(in: items, startIndex: 99)?.mediaType, .image)
        XCTAssertNil(MediaPreviewItem.currentItem(in: [], startIndex: 0))
    }
}
