//
//  LoginState.swift
//  punchnet
//
//  Created by 安礼成 on 2026/1/16.
//

import Foundation
import Observation
import SwiftUI

@Observable
class RegisterModel {
    
    enum Stage {
        case requestVerifyCode(username: String?)
        case submitVerifyCode(username: String, sessionId: Int)
        case setPassword(sessionId: Int)
    }
    
    // 注册会话信息
    struct RegisterSession: Codable {
        let sessionId: Int
        
        enum CodingKeys: String, CodingKey {
            case sessionId = "session_id"
        }
    }
    
    var stage: Stage = .requestVerifyCode(username: nil)
    var transitionEdge: Edge = .trailing // 默认从右进入
    
    private let baseParams: [String: Any] = [
        "client_id": SystemConfig.getClientId(),
        "mac": SystemConfig.macAddressString(mac: SystemConfig.getMacAddress())
    ]
    
    func requestVerifyCode(username: String) async throws -> RegisterSession {
        var params: [String: Any] = [
            "username": username
        ]
        params.merge(baseParams) {$1}
        
        return try await SDLAPIClient.doPost(path: "/register/sendVerfiyCode", params: params, as: RegisterSession.self)
    }
    
    func submitVerifyCode(sessionId: Int, verifyCode: Int) async throws -> String {
        var params: [String: Any] = [
            "session_id": sessionId,
            "code": verifyCode,
        ]
        params.merge(baseParams) {$1}
        
        return try await SDLAPIClient.doPost(path: "/register/verfiyCode", params: params, as: String.self)
    }
    
    func register(sessionId: Int, password: String) async throws -> String {
        var params: [String: Any] = [
            "session_id": sessionId,
            "password": password
        ]
        params.merge(baseParams) {$1}
        
        return try await SDLAPIClient.doPost(path: "/register/submit", params: params, as: String.self)
    }
    
}
