package com.ffii.fpsms.m18.service

import com.ffii.fpsms.api.service.ApiCallerService
import com.ffii.fpsms.m18.M18Config
import com.ffii.fpsms.m18.model.M18TokenRequest
import com.ffii.fpsms.m18.model.M18TokenResponse
import jakarta.annotation.PostConstruct
import org.springframework.context.annotation.Bean
import org.springframework.stereotype.Service


@Service
open class M18TokenService(
    private val apiCallerService: ApiCallerService,
    private val m18Config: M18Config
) {

    @Bean
     fun run() {
//        val params: MutableMap<String, String> = mutableMapOf(
//            "grant_type" to m18Config.GRANT_TYPE,
//            "client_id" to m18Config.CLIENT_ID,
//            "client_secret" to m18Config.CLIENT_SECRET,
//            "username" to m18Config.USERNAME,
//            "password" to m18Config.PASSWORD
//        )
//
        val params = M18TokenRequest(
            grant_type = m18Config.GRANT_TYPE,
            client_id = m18Config.CLIENT_ID,
            client_secret = m18Config.CLIENT_SECRET,
            username = m18Config.USERNAME,
            password = m18Config.PASSWORD
        )

        apiCallerService
            .get<M18TokenResponse, M18TokenRequest>("/oauth/token", params, null)
            .subscribe(
                { response ->
                    m18Config.ACCESS_TOKEN = response.access_token
                    println("WebClient Response stored: $response")
                },
                { error -> println("WebClient Error: ${error.message}") }
            )
    }

}