package com.omixlab.lckcontrol.auth

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.lifecycle.lifecycleScope
import com.omixlab.lckcontrol.MainActivity
import com.omixlab.lckcontrol.data.repository.AccountRepository
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class TwitchAuthRedirectActivity : ComponentActivity() {

    @Inject lateinit var accountRepository: AccountRepository

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val code = intent?.data?.getQueryParameter("code")
        val state = intent?.data?.getQueryParameter("state")

        lifecycleScope.launch {
            if (code != null && state != null) {
                try {
                    accountRepository.handleTwitchCallback(code, state)
                } catch (e: Exception) {
                    Log.e("TwitchAuth", "Callback failed", e)
                }
            }
            val mainIntent = Intent(this@TwitchAuthRedirectActivity, MainActivity::class.java).apply {
                flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
            }
            startActivity(mainIntent)
            finish()
        }
    }
}
