import Foundation

actor AuthenticationService {
    nonisolated(unsafe) static let shared = AuthenticationService()

    private let networkService = NetworkService.shared
    private let storageService = StorageService.shared

    private init() {}

    // DEVELOPMENT: Set to true to allow "1" as a shortcut password (uses stored credentials)
    private let devPasswordShortcutEnabled = true

    func authenticate(password: String) async throws -> XStreamCredentials {
        // Development shortcut: password "1" uses stored credentials if available
        if devPasswordShortcutEnabled && password == "1" {
            if let stored = try await storageService.loadCredentials() {
                print("🔐 Dev shortcut: Using stored credentials")
                return stored
            }
            print("🔐 Dev shortcut: No stored credentials, falling back to normal auth")
        }

        guard let url = URL(string: Constants.API.authenticationBaseURL + Constants.API.authenticationEndpoint) else {
            throw NetworkError.invalidURL
        }

        let headers = [
            Constants.API.authenticationHeaderKey: password
        ]

        do {
            let response: AuthResponse = try await networkService.request(
                url: url,
                method: .get,
                headers: headers
            )

            let credentials = response.toXStreamCredentials()

            try await storageService.saveCredentials(credentials)

            return credentials

        } catch let error as NetworkError {
            throw error
        } catch {
            throw NetworkError.authenticationFailed
        }
    }

    func loadStoredCredentials() async throws -> XStreamCredentials? {
        return try await storageService.loadCredentials()
    }

    func logout() async throws {
        try await storageService.clearCredentials()
    }

    func hasStoredCredentials() async -> Bool {
        do {
            let credentials = try await storageService.loadCredentials()
            return credentials != nil
        } catch {
            return false
        }
    }
}
