import Combine
import Foundation
import SwiftUI

// MARK: - GroupSetupViewModel

/// ViewModel for the two-step group creation flow.
/// Matches Android `GroupSetupScreen.kt` behavior.
@MainActor
final class GroupSetupViewModel: ObservableObject {
    @Published var title: String = ""
    @Published var groupDescription: String = ""
    @Published var isCreating: Bool = false
    @Published var errorMessage: String?
    @Published var createdRoute: ChatRoute?

    /// Maximum character limits (Android parity).
    static let maxTitleLength = 80
    static let maxDescriptionLength = 400

    var canCreate: Bool {
        !title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !isCreating
    }

    func createGroup() async {
        guard canCreate else { return }
        isCreating = true
        errorMessage = nil

        do {
            let route = try await GroupService.shared.createGroup(
                title: title.trimmingCharacters(in: .whitespacesAndNewlines),
                description: groupDescription.trimmingCharacters(in: .whitespacesAndNewlines)
            )
            createdRoute = route
        } catch {
            errorMessage = error.localizedDescription
        }

        isCreating = false
    }
}
