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

import Foundation
import Observation
import SwiftUI

@Observable
class ResetPasswordModel {
    
    enum Stage {
        case requestVerifyCode(username: String?)
        case submitVerifyCode(username: String, sessionId: Int)
        case resetPassword(username: String, sessionId: Int)
    }
     
    var stage: Stage = .requestVerifyCode(username: nil)
    var transitionEdge: Edge = .trailing // 默认从右进入
    
    // 重置会话信息
    struct ResetPasswordSession: Codable {
        let sessionId: Int
        
        enum CodingKeys: String, CodingKey {
            case sessionId = "session_id"
        }
    }
    
    private let baseParams: [String: Any] = [
        "client_id": SystemConfig.getClientId(),
        "mac": SystemConfig.macAddressString(mac: SystemConfig.getMacAddress())
    ]
    
    func requestVerifyCode(username: String) async throws -> ResetPasswordSession {
        var params: [String: Any] = [
            "username": username
        ]
        params.merge(baseParams) {$1}
        
        return try await SDLAPIClient.doPost(path: "/password/sendVerfiyCode", params: params, as: ResetPasswordSession.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: "/password/verfiyCode", params: params, as: String.self)
    }
    
    func resetPassword(sessionId: Int, newPassword: String) async throws -> String {
        var params: [String: Any] = [
            "session_id": sessionId,
            "new_password": newPassword,
        ]
        params.merge(baseParams) {$1}
        
        return try await SDLAPIClient.doPost(path: "/password/reset", params: params, as: String.self)
    }
    
}
