//
//  CooperationOrderListViewModelTests.swift
//  suixinkanTests
//

import XCTest
@testable import suixinkan

@MainActor
final class CooperationOrderListViewModelTests: XCTestCase {

    func testRefreshLeadsLoadsFirstPage() async throws {
        let json = """
        {"code":100000,"msg":"success","data":{"total":1,"list":[{"id":1,"user_phone":"13800138000","created_at":"2026-01-01"}]}}
        """.data(using: .utf8)!
        let api = OrderAPI(client: APIClient(environment: .testing, session: MockURLSession(responses: [json])))
        let viewModel = CooperationOrderListViewModel()

        await viewModel.refreshLeads(api: api)

        XCTAssertEqual(viewModel.leads.count, 1)
        XCTAssertFalse(viewModel.canLoadMore)
        XCTAssertFalse(viewModel.isRefreshing)
    }

    func testSearchUsesKeywordQuery() async throws {
        let json = """
        {"code":100000,"msg":"success","data":{"total":0,"list":[]}}
        """.data(using: .utf8)!
        let session = MockURLSession(responses: [json])
        let api = OrderAPI(client: APIClient(environment: .testing, session: session))
        let viewModel = CooperationOrderListViewModel()
        viewModel.onTabSelected(1)
        viewModel.onSearchTextChange("张三")

        await viewModel.refreshAcquisitionOrders(api: api)

        let url = try XCTUnwrap(session.requests.first?.url?.absoluteString)
        XCTAssertTrue(url.contains("acquisition-orders"))
        XCTAssertTrue(url.contains("keyword="))
    }

    func testLoadMoreAppendsLeads() async throws {
        let page1 = """
        {"code":100000,"msg":"success","data":{"total":2,"list":[{"id":1,"user_phone":"13800138000"}]}}
        """.data(using: .utf8)!
        let page2 = """
        {"code":100000,"msg":"success","data":{"total":2,"list":[{"id":2,"user_phone":"13800138001"}]}}
        """.data(using: .utf8)!
        let api = OrderAPI(client: APIClient(environment: .testing, session: MockURLSession(responses: [page1, page2])))
        let viewModel = CooperationOrderListViewModel()

        await viewModel.refreshLeads(api: api)
        await viewModel.loadMore(api: api)

        XCTAssertEqual(viewModel.leads.count, 2)
    }

    func testShouldLoadMoreNearEnd() {
        let viewModel = CooperationOrderListViewModel()
        XCTAssertFalse(viewModel.shouldLoadMore(at: 0))
    }
}
