import Foundation
import ComposeApp
import Combine

/// ViewModel for email verification.
/// Calls APILayer directly for verification.
@MainActor
class VerifyEmailViewModel: ObservableObject {
    // MARK: - Published Properties
    @Published var code: String = ""
    @Published var isLoading: Bool = false
    @Published var errorMessage: String?
    @Published var isVerified: Bool = false

    // MARK: - Private Properties
    private let tokenStorage: TokenStorageProtocol
    private let dataManager: DataManagerObservable

    // MARK: - Initialization
    init(
        tokenStorage: TokenStorageProtocol? = nil,
        dataManager: DataManagerObservable = .shared
    ) {
        self.tokenStorage = tokenStorage ?? Dependencies.current.makeTokenStorage()
        self.dataManager = dataManager
    }

    // MARK: - Public Methods
    func verifyEmail() {
        // Validation using ValidationRules
        if let error = ValidationRules.validateCode(code, expectedLength: 6) {
            errorMessage = error.errorDescription
            return
        }

        guard let token = tokenStorage.getToken() else {
            errorMessage = "Not authenticated"
            return
        }

        isLoading = true
        errorMessage = nil

        Task {
            do {
                let request = VerifyEmailRequest(code: code)
                let result = try await APILayer.shared.verifyEmail(token: token, request: request)

                if let success = result as? ApiResultSuccess<VerifyEmailResponse>, let response = success.data {
                    print("VerifyEmailViewModel: onSuccess called, verified=\(response.verified)")
                    if response.verified {
                        print("VerifyEmailViewModel: Setting isVerified = true")
                        self.isVerified = true
                        self.isLoading = false
                        print("VerifyEmailViewModel: isVerified is now \(self.isVerified)")
                    } else {
                        self.errorMessage = "Verification failed"
                        self.isLoading = false
                    }
                } else if let error = ApiResultBridge.error(from: result) {
                    self.errorMessage = ErrorMessageParser.parse(error.message)
                    self.isLoading = false
                } else {
                    self.errorMessage = "Failed to verify email"
                    self.isLoading = false
                }
            } catch {
                self.errorMessage = ErrorMessageParser.parse(error.localizedDescription)
                self.isLoading = false
            }
        }
    }

    func clearError() {
        errorMessage = nil
    }
}
