import Foundation
import SwiftUI
import Combine

@MainActor
class PDSViewModel: ObservableObject {
    @Published var pdsService = PDSService()
    @Published var alertItem: AlertItem?
    
    var errorMessage: String? {
        pdsService.errorMessage
    }
    
    var isLoading: Bool {
        pdsService.isLoading
    }
    
    var isAuthenticated: Bool {
        get {
            let value = pdsService.isAuthenticated
            print("PDSViewModel: isAuthenticated getter called, value = \(value)")
            return value
        }
    }
    
    var users: [PDSUser] {
        pdsService.users
    }
    
    var inviteCodes: [InviteCode] {
        pdsService.inviteCodes
    }
    
    func login(serverURL: String, username: String, password: String) async {
        print("PDSViewModel: login called")
        if let credentials = PDSCredentials(serverURL: serverURL, username: username, password: password) {
            let success = await pdsService.login(credentials: credentials)
            print("PDSViewModel: login completed, success = \(success), isAuthenticated = \(pdsService.isAuthenticated)")
            
            // Force update the view by triggering objectWillChange
            objectWillChange.send()
        } else {
            pdsService.errorMessage = "Invalid credentials"
        }
    }
    
    func logout() {
        print("PDSViewModel: logout called")
        pdsService.logout()
        objectWillChange.send()
    }
}

struct AlertItem: Identifiable {
    let id = UUID()
    let title: String
    let message: String
} 