//
//  TaskAPI.swift
//  suixinkan
//
//  Created by Codex on 2026/6/23.
//

import Foundation
import Combine

/// 任务服务协议，抽象任务列表、详情、发布和云盘选择接口以便测试替换。
@MainActor
protocol TaskServing {
    /// 获取摄影师任务列表。
    func taskList(
        scenicId: Int,
        page: Int,
        pageSize: Int,
        taskStatus: Int,
        taskName: String?,
        startTime: String?,
        endTime: String?
    ) async throws -> ListPayload<PhotographerTaskItem>

    /// 获取任务详情。
    func taskDetail(id: Int) async throws -> TaskDetailResponse

    /// 获取发布任务时可关联的订单列表。
    func availableOrderList(scenicId: Int) async throws -> [AvailableOrderResponse]

    /// 发布任务。
    func addTask(_ request: AddTaskRequest) async throws

    /// 获取云盘文件列表，供发布任务选择附件。
    func cloudFileList(
        parentFolderId: Int,
        name: String,
        type: Int,
        orderBy: Int,
        page: Int,
        pageSize: Int
    ) async throws -> ListPayload<CloudDriveFile>
}

/// 任务 API，封装任务管理和发布任务相关接口。
@MainActor
final class TaskAPI: TaskServing {
    private let client: APIClient

    /// 初始化任务 API，并注入共享网络客户端。
    init(client: APIClient) {
        self.client = client
    }

    /// 获取摄影师任务列表。
    func taskList(
        scenicId: Int,
        page: Int = 1,
        pageSize: Int = 10,
        taskStatus: Int = 0,
        taskName: String? = nil,
        startTime: String? = nil,
        endTime: String? = nil
    ) async throws -> ListPayload<PhotographerTaskItem> {
        var query = [
            URLQueryItem(name: "scenic_id", value: "\(scenicId)"),
            URLQueryItem(name: "page", value: "\(max(page, 1))"),
            URLQueryItem(name: "page_size", value: "\(max(pageSize, 1))"),
            URLQueryItem(name: "task_status", value: "\(max(taskStatus, 0))")
        ]
        if let taskName = taskName?.trimmingCharacters(in: .whitespacesAndNewlines), !taskName.isEmpty {
            query.append(URLQueryItem(name: "task_name", value: taskName))
        }
        if let startTime, !startTime.isEmpty {
            query.append(URLQueryItem(name: "start_time", value: startTime))
        }
        if let endTime, !endTime.isEmpty {
            query.append(URLQueryItem(name: "end_time", value: endTime))
        }

        return try await client.send(
            APIRequest(
                method: .get,
                path: "/api/yf-handset-app/photog/task/list",
                queryItems: query
            )
        )
    }

    /// 获取任务详情。
    func taskDetail(id: Int) async throws -> TaskDetailResponse {
        try await client.send(
            APIRequest(
                method: .get,
                path: "/api/yf-handset-app/photog/task/info",
                queryItems: [URLQueryItem(name: "id", value: "\(id)")]
            )
        )
    }

    /// 获取发布任务时可关联的订单列表。
    func availableOrderList(scenicId: Int) async throws -> [AvailableOrderResponse] {
        try await client.send(
            APIRequest(
                method: .get,
                path: "/api/yf-handset-app/photog/task/available-order",
                queryItems: [URLQueryItem(name: "scenic_id", value: "\(scenicId)")]
            )
        )
    }

    /// 发布任务。
    func addTask(_ request: AddTaskRequest) async throws {
        _ = try await client.send(
            APIRequest(
                method: .post,
                path: "/api/yf-handset-app/photog/task/create",
                body: request
            )
        ) as EmptyPayload
    }

    /// 获取云盘文件列表，供发布任务选择附件。
    func cloudFileList(
        parentFolderId: Int,
        name: String = "",
        type: Int = 0,
        orderBy: Int = 2,
        page: Int = 1,
        pageSize: Int = 20
    ) async throws -> ListPayload<CloudDriveFile> {
        try await client.send(
            APIRequest(
                method: .get,
                path: "/api/yf-handset-app/photog/cloud-driver/list",
                queryItems: [
                    URLQueryItem(name: "parent_folder_id", value: "\(parentFolderId)"),
                    URLQueryItem(name: "name", value: name),
                    URLQueryItem(name: "type", value: "\(type)"),
                    URLQueryItem(name: "order_by", value: "\(orderBy)"),
                    URLQueryItem(name: "page", value: "\(max(page, 1))"),
                    URLQueryItem(name: "page_size", value: "\(max(pageSize, 1))")
                ]
            )
        )
    }
}
