//
//  AuthApi.swift

//
//  Created by Leon on 2025/7/28.
//

import Foundation
import Moya

enum RegisterType: String {
    case EMAIL
    case MOBILE
    case THIRD
}

enum SMSCodeType: Int {
    case email = 0
    case mobile_login = 1
    case reset_password = 2
}

enum LoginSMSCodeFrom: String {
    case WHATS_APP
    case MOBILE
}

enum SendTypeEnum: String {
    case SMS
    case WHATS_APP
}

enum ThirdType: String, Codable {
    case APPLE = "APPLE"
    case GOOGLE = "GOOGLE"
    case DISCORD = "DISCORD"
}

// let LoginProvider = MoyaProvider<LoginAPI>(requestClosure: myRequestClosure)

// MoyaProvider.immediatelyStub
let LoginProvider = APIConfig.useMock && LoginAPI.useMock
    ? MoyaProvider<LoginAPI>(endpointClosure: myEndpointClosure, stubClosure: { target in
        let data = target.sampleData
        if data.count > 0 {
            return .delayed(seconds: 0.5)
        } else {
            return .never
        }
    })
    : MoyaProvider<LoginAPI>(requestClosure: myRequestClosure)

enum LoginAPI {
    static let useMock: Bool = false
    
    /// 三方账号注册登陆
    case loginByThird(params: [String: Any])

    case registerThird(thirdToken: String, thirdType: ThirdType = .APPLE, nickname: String)
    /// 完善用户基础信息
    case completeUserInfo(params: [String: Any])
}

extension LoginAPI: TargetType {
    var baseURL: URL {
        return URL(string: APIConfig.frog)!
    }

    var path: String {
        switch self {
        case .loginByThird:
            return "/web/third/login"
        case .registerThird:
            return "/mobile/user/register/by-third"
        case .completeUserInfo:
            return "/web/user/complete-user-info"
        }
    }

    var method: Moya.Method {
        return .post
    }

//    var sampleData: Data {
//        return "".data(using: String.Encoding.utf8)!
//    }

    var task: Task {
        var mParams = [String: Any]()

        switch self {
        case let .loginByThird(params):
            mParams = params
        case let .registerThird(thirdToken, thirdType, nickname):
            mParams = ["thirdToken": thirdToken, "thirdType": thirdType.rawValue, "nickname": nickname]
        case let .completeUserInfo(params):
            mParams = params
        }

        mParams.updateValue("IOS", forKey: "appClient")
        mParams.updateValue(UIDevice.UUID, forKey: "deviceCode")

//        if let code = HCaptchaHandler.shared.reqValidateCodeForLoginAPI {
//            mParams.updateValue(code, forKey: "reqValidateCode")
//        }

        return .requestParameters(parameters: mParams, encoding: JSONEncoding.default)
    }

    var headers: [String: String]? {
        return APIConfig.apiHeaders()
    }

    static func getGMTFlagForSignUp() -> String? {
        if let abbreviation = TimeZone.current.abbreviation() {
            let pure = abbreviation.replacingOccurrences(of: "GMT", with: "")
            if let gmt = Int(pure) {
                if gmt > 0 {
                    let format = String(format: "+%02d", gmt)
                    dlog("❇️ GMT Flag: \(format)")
                    return format
                } else {
                    let format = String(format: "-%02d", gmt)
                    dlog("❇️ GMT Flag: \(format)")
                    return format
                }
            }
        }
        return nil
    }

    var sampleData: Data {
        switch self {
        case .loginByThird:
            let content = """
                            {
                                "token": "LvRK8TGeMGbPRfQWeyuSV4o0XqXkDJDN"
                              }
                            """
            return .okContent(string: content)
        case .completeUserInfo:
            let mockJSON = """
            {
              "status" : "OK",
              "errorCode" : null,
              "content" : null,
              "errorMsg" : null,
              "traceId" : "b46cb53f-550c-46aa-8ccd-28f968f97e0a"
            }
            """
            return Data(mockJSON.utf8)
        default:
            return Data()
        }
    }
}
