//
//  SelectAcademyViewModel.swift
//  AcaMate
//
//  Created by TAnine on 2/19/25.
//

import SwiftUI
import Combine

class SelectAcademyViewModel: ObservableObject {
    private var appVM: AppViewModel
    private var cancellables: Set<AnyCancellable> = []
    
    init(_ appVM: AppViewModel) {
        self.appVM = appVM
    }
    
    @Published var academyCode: String = ""
    @Published var academyList: [AcademyName] = []
    @Published var selectNum: Int = -1
    
    func moveChatting() {
        appVM.naviState.set(act: .RESET, path: .Main)
    }
    
    
    func loadAcademy() {
        @UserDefault(key: "token", defaultValue: "accToken") var token
        @UserDefault(key: "refresh", defaultValue: "refreshToken") var refresh
        
        let request = APIRequest(path: "/api/v1/in/user/academy",
                                 parameters: ["token": token, "refresh": refresh],
                                 decoding: APIResponse<[AcademyName]>.self)
        
        appVM.apiManager.loadAPIData(request)
        .sink { completion in
            switch completion {
            case .failure(let error):
                printLog("\(error)")
            case .finished:
                break
            }
        } receiveValue: { [weak self] response in
            guard let self = self else {return}
            guard let academyNames = response as? APIResponse<[AcademyName]> else {return}
            guard let academyList = academyNames.data else { return }
            self.academyList = academyList
        }
        .store(in: &cancellables)
    }
    
    func toggleSelection(for index: Int){
        if selectNum == index {
            selectNum = -1
        } else {
            selectNum = index
        }
    }
    
    
}
