//
//  CooperationOrderAPI.swift
//  suixinkan
//
//  Created by Codex on 2026/6/29.
//

import Foundation

@MainActor
/// 合作订单服务协议，抽象获客员与带客单相关接口以便测试替换。
protocol CooperationOrderServing {
    /// 获取合作获客员列表。
    func cooperativeSalers(storeId: Int?, page: Int, pageSize: Int) async throws -> CooperativeSalerListPayload

    /// 获取获客员邀请信息。
    func saleUserInviteInfo(saleUserId: Int) async throws -> SaleUserInviteInfo

    /// 接受获客员绑定。
    func saleUserAcceptBind(saleUserId: Int, commissionRate: Int) async throws

    /// 获取获客员线索列表。
    func saleUserReferralLeads(page: Int, pageSize: Int) async throws -> ListPayload<ReferralLead>

    /// 获取获客订单列表。
    func saleUserAcquisitionOrders(keyword: String?, page: Int, pageSize: Int) async throws -> ListPayload<AcquisitionOrder>

    /// 获取可绑定带客单列表。
    func saleUserReferralOrders(saleUserId: Int, page: Int, pageSize: Int) async throws -> ReferralOrderListPayload

    /// 绑定带客单到订单。
    func saleUserBindReferralOrder(orderNumber: String, referralOrderNo: String) async throws

    /// 更新带客单状态（如退款时 status=3）。
    func saleUserUpdateReferralOrderStatus(id: Int, status: Int) async throws

    /// 更新合作获客员备注名。
    func saleUserUpdateRemark(saleUserId: Int, photogRemarkName: String) async throws

    /// 发送修改分成比例短信验证码。
    func saleUserCommissionRateSendSmsCode(phone: String) async throws

    /// 更新合作获客员分成比例。
    func saleUserUpdateCommissionRate(saleUserId: Int, commissionRate: Int, smsCode: String) async throws -> CooperativeSaler
}

@MainActor
/// 合作订单 API，封装合作获客员、线索、获客订单与带客单绑定接口。
final class CooperationOrderAPI: CooperationOrderServing {
    private let client: APIClient

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

    /// 获取合作获客员列表。
    func cooperativeSalers(storeId: Int? = nil, page: Int = 1, pageSize: Int = 10) async throws -> CooperativeSalerListPayload {
        var query = [
            URLQueryItem(name: "page", value: "\(max(page, 1))"),
            URLQueryItem(name: "page_size", value: "\(max(pageSize, 1))")
        ]
        if let storeId, storeId > 0 {
            query.append(URLQueryItem(name: "store_id", value: "\(storeId)"))
        }
        return try await client.send(
            APIRequest(
                method: .get,
                path: "/api/yf-handset-app/photog/cooperative-salers",
                queryItems: query
            )
        )
    }

    /// 获取获客员邀请信息。
    func saleUserInviteInfo(saleUserId: Int) async throws -> SaleUserInviteInfo {
        try await client.send(
            APIRequest(
                method: .get,
                path: "/api/yf-handset-app/photog/sale-user/invite-info",
                queryItems: [URLQueryItem(name: "sale_user_id", value: "\(saleUserId)")]
            )
        )
    }

    /// 接受获客员绑定。
    func saleUserAcceptBind(saleUserId: Int, commissionRate: Int) async throws {
        let _: EmptyPayload = try await client.send(
            APIRequest(
                method: .post,
                path: "/api/yf-handset-app/photog/sale-user/accept-bind",
                queryItems: [
                    URLQueryItem(name: "sale_user_id", value: "\(saleUserId)"),
                    URLQueryItem(name: "commission_rate", value: "\(commissionRate)"),
                ]
            )
        )
    }

    /// 获取获客员线索列表。
    func saleUserReferralLeads(page: Int = 1, pageSize: Int = 10) async throws -> ListPayload<ReferralLead> {
        try await client.send(
            APIRequest(
                method: .get,
                path: "/api/yf-handset-app/photog/sale-user/referral-leads",
                queryItems: [
                    URLQueryItem(name: "page", value: "\(max(page, 1))"),
                    URLQueryItem(name: "page_size", value: "\(max(pageSize, 1))")
                ]
            )
        )
    }

    /// 获取获客订单列表。
    func saleUserAcquisitionOrders(keyword: String? = nil, page: Int = 1, pageSize: Int = 10) async throws -> ListPayload<AcquisitionOrder> {
        var query = [
            URLQueryItem(name: "page", value: "\(max(page, 1))"),
            URLQueryItem(name: "page_size", value: "\(max(pageSize, 1))")
        ]
        if let keyword, !keyword.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
            query.append(URLQueryItem(name: "keyword", value: keyword))
        }
        return try await client.send(
            APIRequest(
                method: .get,
                path: "/api/yf-handset-app/photog/sale-user/acquisition-orders",
                queryItems: query
            )
        )
    }

    /// 获取可绑定带客单列表。
    func saleUserReferralOrders(saleUserId: Int, page: Int = 1, pageSize: Int = 10) async throws -> ReferralOrderListPayload {
        try await client.send(
            APIRequest(
                method: .get,
                path: "/api/yf-handset-app/photog/sale-user/referral-orders",
                queryItems: [
                    URLQueryItem(name: "sale_user_id", value: "\(saleUserId)"),
                    URLQueryItem(name: "page", value: "\(max(page, 1))"),
                    URLQueryItem(name: "page_size", value: "\(max(pageSize, 1))")
                ]
            )
        )
    }

    /// 绑定带客单到订单。
    func saleUserBindReferralOrder(orderNumber: String, referralOrderNo: String) async throws {
        let _: EmptyPayload = try await client.send(
            APIRequest(
                method: .post,
                path: "/api/yf-handset-app/photog/sale-user/bind-referral-order",
                queryItems: [
                    URLQueryItem(name: "order_number", value: orderNumber),
                    URLQueryItem(name: "referral_order_no", value: referralOrderNo)
                ]
            )
        )
    }

    /// 更新带客单状态。
    func saleUserUpdateReferralOrderStatus(id: Int, status: Int) async throws {
        let _: EmptyPayload = try await client.send(
            APIRequest(
                method: .post,
                path: "/api/yf-handset-app/photog/sale-user/referral-orders/\(id)/status",
                body: ReferralOrderStatusUpdateRequest(status: status)
            )
        )
    }

    /// 更新合作获客员备注名。
    func saleUserUpdateRemark(saleUserId: Int, photogRemarkName: String) async throws {
        let _: EmptyPayload = try await client.send(
            APIRequest(
                method: .post,
                path: "/api/yf-handset-app/photog/sale-user/update-remark",
                body: SaleUserUpdateRemarkRequest(
                    saleUserId: saleUserId,
                    photogRemarkName: photogRemarkName
                )
            )
        )
    }

    /// 发送修改分成比例短信验证码。
    func saleUserCommissionRateSendSmsCode(phone: String) async throws {
        let _: EmptyPayload = try await client.send(
            APIRequest(
                method: .post,
                path: "/api/yf-handset-app/photog/sale-user/commission-rate/send-sms-code",
                body: SaleUserCommissionRateSmsRequest(phone: phone)
            )
        )
    }

    /// 更新合作获客员分成比例。
    func saleUserUpdateCommissionRate(
        saleUserId: Int,
        commissionRate: Int,
        smsCode: String
    ) async throws -> CooperativeSaler {
        try await client.send(
            APIRequest(
                method: .post,
                path: "/api/yf-handset-app/photog/sale-user/commission-rate",
                body: SaleUserCommissionRateUpdateRequest(
                    saleUserId: saleUserId,
                    commissionRate: commissionRate,
                    smsCode: smsCode
                )
            )
        )
    }
}
