//
//  PunchPointAPI.swift
//  suixinkan
//
//  Created by Codex on 2026/6/24.
//

import Foundation
import Combine

/// 打卡点服务协议，抽象列表、详情和增删改接口以便单元测试替换。
@MainActor
protocol PunchPointServing {
    /// 获取指定景区的打卡点列表。
    func punchPointList(scenicId: Int, status: Int, page: Int, pageSize: Int) async throws -> ListPayload<PunchPointItem>

    /// 获取指定打卡点详情。
    func punchPointInfo(id: Int) async throws -> PunchPointItem

    /// 新增打卡点。
    func addPunchPoint(_ request: AddPunchPointRequest) async throws

    /// 编辑打卡点。
    func editPunchPoint(_ request: EditPunchPointRequest) async throws

    /// 删除打卡点。
    func deletePunchPoint(id: Int) async throws
}

/// 打卡点 API，负责封装旧工程打卡点管理相关接口。
@MainActor
final class PunchPointAPI: PunchPointServing {
    private let client: APIClient

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

    /// 获取指定景区的打卡点列表。
    func punchPointList(scenicId: Int, status: Int = 0, page: Int = 1, pageSize: Int = 20) async throws -> ListPayload<PunchPointItem> {
        try await client.send(
            APIRequest(
                method: .get,
                path: "/api/yf-handset-app/photog/scenic-spot/list",
                queryItems: [
                    URLQueryItem(name: "scenic_area_id", value: "\(scenicId)"),
                    URLQueryItem(name: "status", value: "\(max(status, 0))"),
                    URLQueryItem(name: "page", value: "\(max(page, 1))"),
                    URLQueryItem(name: "page_size", value: "\(max(pageSize, 1))")
                ]
            )
        )
    }

    /// 获取指定打卡点详情。
    func punchPointInfo(id: Int) async throws -> PunchPointItem {
        try await client.send(
            APIRequest(
                method: .get,
                path: "/api/yf-handset-app/photog/scenic-spot/info",
                queryItems: [URLQueryItem(name: "id", value: "\(id)")]
            )
        )
    }

    /// 新增打卡点。
    func addPunchPoint(_ request: AddPunchPointRequest) async throws {
        _ = try await client.send(
            APIRequest(method: .post, path: "/api/yf-handset-app/photog/scenic-spot/add", body: request)
        ) as EmptyPayload
    }

    /// 编辑打卡点。
    func editPunchPoint(_ request: EditPunchPointRequest) async throws {
        _ = try await client.send(
            APIRequest(method: .post, path: "/api/yf-handset-app/photog/scenic-spot/edit", body: request)
        ) as EmptyPayload
    }

    /// 删除打卡点。
    func deletePunchPoint(id: Int) async throws {
        _ = try await client.send(
            APIRequest(method: .post, path: "/api/yf-handset-app/photog/scenic-spot/delete", body: PunchPointDeleteRequest(id: id))
        ) as EmptyPayload
    }
}
