//
//  LiveApi.swift
//  SodaLive
//
//  Created by klaus on 2023/08/09.
//

import Foundation
import Moya

enum LiveApi {
    case roomList(request: GetRoomListRequest)
    case recentVisitRoomUsers
    case getReservations(isActive: Bool)
    case getReservation(reservationId: Int)
    case cancelReservation(request: CancelLiveReservationRequest)
}

extension LiveApi: TargetType {
    var baseURL: URL {
        return URL(string: BASE_URL)!
    }
    
    var path: String {
        switch self {
        case .roomList:
            return "/live/room"
            
        case .recentVisitRoomUsers:
            return "/live/room/recent_visit_room/users"
            
        case .getReservations:
            return "/live/reservation"
            
        case .getReservation(let reservationId):
            return "/live/reservation/\(reservationId)"
            
        case .cancelReservation:
            return "/live/reservation/cancel"
        }
    }
    
    var method: Moya.Method {
        switch self {
        case .roomList, .recentVisitRoomUsers, .getReservations, .getReservation:
            return .get
            
        case .cancelReservation:
            return .put
        }
    }
    
    var task: Moya.Task {
        switch self {
        case .roomList(let request):
            var parameters = [
                "timezone": request.timezone,
                "status": request.status.rawValue,
                "page": request.page - 1,
                "size": request.size,
            ] as [String : Any]
            
            if let dateString = request.dateString {
                parameters["dateString"] = dateString
            }
            
            return .requestParameters(
                parameters: parameters,
                encoding: URLEncoding.queryString)
            
        case .recentVisitRoomUsers:
            return .requestPlain
            
        case .getReservations(let isActive):
            let parameters = [
                "timezone": TimeZone.current.identifier,
                "isActive": isActive
            ] as [String : Any]
            
            return .requestParameters(
                parameters: parameters,
                encoding: URLEncoding.queryString
            )
            
        case .getReservation:
            let parameters = ["timezone": TimeZone.current.identifier] as [String : Any]
            
            return .requestParameters(
                parameters: parameters,
                encoding: URLEncoding.queryString
            )
            
        case .cancelReservation(let request):
            return .requestJSONEncodable(request)
        }
    }
    
    var headers: [String : String]? {
        return ["Authorization": "Bearer \(UserDefaults.string(forKey: UserDefaultsKey.token))"]
    }
}
