import Foundation

@MainActor
final class AuthViewModel: ObservableObject {
    enum Mode: String, CaseIterable {
        case login
        case register
    }

    static let tokenKey = "bookibra.jwt"
    static let emailKey = "bookibra.email"

    @Published var mode: Mode = .login
    @Published var email = ""
    @Published var password = ""
    @Published var isLoading = false
    @Published var errorMessage: String?

    private let authService: AuthServiceProtocol
    private let keychain: KeychainStoreProtocol

    init(authService: AuthServiceProtocol, keychain: KeychainStoreProtocol) {
        self.authService = authService
        self.keychain = keychain
    }

    func submit(onSuccess: @escaping () -> Void) async {
        guard !email.isEmpty, !password.isEmpty else {
            errorMessage = "E-posta ve şifre gerekli"
            return
        }

        isLoading = true
        defer { isLoading = false }

        do {
            let response: AuthResponse
            switch mode {
            case .login:
                response = try await authService.login(email: email, password: password)
            case .register:
                response = try await authService.register(email: email, password: password)
            }

            _ = try await authService.profile(token: response.token)
            _ = keychain.save(response.token, for: Self.tokenKey)
            _ = keychain.save(response.user.email, for: Self.emailKey)
            onSuccess()
        } catch {
            errorMessage = error.localizedDescription
        }
    }
}
