import SwiftUI

@MainActor
final class AppState: ObservableObject {
    @Published var userId: Int?
    @Published var userName: String?
    @Published var userPhotoUrl: String?
    @Published var userToken: String?
    @Published var businessId: Int = 0
    @Published var roleId: Int = 1  // 1=Staff, 2=Manager, 3=Admin
    @Published var isAuthenticated = false
    @Published var shouldPopToRoot = false
    @Published var shouldPopToTaskList = false
    @Published var needsRefresh = false

    /// Navigate back to root (business selection) and trigger a data refresh
    func popToRoot() {
        needsRefresh = true
        shouldPopToRoot = true
    }

    /// Navigate back to task list (not all the way to business selection)
    func popToTaskList() {
        needsRefresh = true
        shouldPopToTaskList = true
    }

    var isLoggedIn: Bool { userId != nil && userToken != nil }

    func setAuth(userId: Int, token: String, userName: String? = nil, photoUrl: String? = nil) {
        self.userId = userId
        self.userToken = token
        self.userName = userName
        self.userPhotoUrl = photoUrl
        self.isAuthenticated = true
    }

    func setBusinessId(_ id: Int, roleId: Int = 1) {
        self.businessId = id
        self.roleId = roleId
    }

    /// Human-readable role name
    var roleName: String {
        switch roleId {
        case 1: return "Staff"
        case 2: return "Manager"
        case 3: return "Admin"
        default: return "Staff"
        }
    }

    func clearAuth() {
        userId = nil
        userToken = nil
        userName = nil
        userPhotoUrl = nil
        isAuthenticated = false
        businessId = 0
    }

    func loadSavedAuth() async {
        let creds = await AuthStorage.shared.loadAuth()
        guard let creds = creds else { return }
        await APIService.shared.setAuth(token: creds.token, userId: creds.userId)
        setAuth(userId: creds.userId, token: creds.token, userName: creds.userName, photoUrl: creds.photoUrl)
    }
}
