import Foundation

public struct PersistedAuthState: Codable, Sendable {
    public var username: String
    public var password: String
    public var kraSessionToken: String?
    public var streamCinemaAuthToken: String?

    public init(
        username: String,
        password: String,
        kraSessionToken: String?,
        streamCinemaAuthToken: String?
    ) {
        self.username = username
        self.password = password
        self.kraSessionToken = kraSessionToken
        self.streamCinemaAuthToken = streamCinemaAuthToken
    }
}

public actor AuthStateStore {
    private let keychain: KeychainStore
    private let key = "auth-state"
    private let encoder = JSONEncoder()
    private let decoder = JSONDecoder()

    public init(keychain: KeychainStore = .init()) {
        self.keychain = keychain
    }

    public func save(_ state: PersistedAuthState) throws {
        let data = try encoder.encode(state)
        try keychain.save(data, for: key)
    }

    public func load() throws -> PersistedAuthState? {
        guard let data = try keychain.read(account: key) else {
            return nil
        }
        return try decoder.decode(PersistedAuthState.self, from: data)
    }

    public func clear() throws {
        try keychain.delete(account: key)
    }
}
