//
//  PollVotingViewModel.swift
//  SportsTime
//
//  ViewModel for voting on trip polls
//

import Foundation
import SwiftUI

@Observable
@MainActor
final class PollVotingViewModel {
    var rankings: [Int] = []  // Trip indices in preference order
    var isLoading = false
    var error: PollError?
    var didSubmit = false

    private let pollService = PollService.shared

    var canSubmit: Bool {
        !rankings.isEmpty
    }

    func initializeRankings(tripCount: Int, existingVote: PollVote?) {
        if let vote = existingVote {
            rankings = vote.rankings
        } else {
            // Default: trips in original order
            rankings = Array(0..<tripCount)
        }
    }

    func moveTrip(from source: IndexSet, to destination: Int) {
        rankings.move(fromOffsets: source, toOffset: destination)
    }

    func submitVote(pollId: UUID) async {
        guard canSubmit else { return }

        isLoading = true
        error = nil

        do {
            let userId = try await pollService.getCurrentUserRecordID()

            let vote = PollVote(
                pollId: pollId,
                odg: userId,
                rankings: rankings
            )

            _ = try await pollService.submitVote(vote)
            didSubmit = true
        } catch let pollError as PollError {
            error = pollError
        } catch {
            self.error = .unknown(error)
        }

        isLoading = false
    }

    func updateVote(existingVote: PollVote) async {
        guard canSubmit else { return }

        isLoading = true
        error = nil

        do {
            var updatedVote = existingVote
            updatedVote.rankings = rankings

            _ = try await pollService.updateVote(updatedVote)
            didSubmit = true
        } catch let pollError as PollError {
            error = pollError
        } catch {
            self.error = .unknown(error)
        }

        isLoading = false
    }

    func reset() {
        rankings = []
        error = nil
        didSubmit = false
    }
}
