package com.syncflow.ui.auth

import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.lifecycle.lifecycleScope
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.syncflow.data.security.CredentialStore
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject

@AndroidEntryPoint
class OAuthRedirectActivity : ComponentActivity() {

    @Inject lateinit var credentialStore: CredentialStore

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

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        handleIntent(intent)
    }

    private fun handleIntent(intent: Intent) {
        val uri = intent.data ?: run { finish(); return }
        val code = uri.getQueryParameter("code") ?: run { finish(); return }
        val returnedState = uri.getQueryParameter("state") ?: run { finish(); return }

        val provider = when {
            uri.host == "oauth" && uri.path?.contains("dropbox") == true -> "dropbox"
            uri.host == "oauth" && uri.path?.contains("onedrive") == true -> "onedrive"
            else -> run { finish(); return }
        }

        // Validate state before doing anything with the code (CSRF protection)
        val storedState = credentialStore.getPkceVerifier("${provider}_state")
        if (storedState == null || returnedState != storedState) {
            finish()
            return
        }
        credentialStore.removePkceVerifier("${provider}_state")

        val appKey = getString(com.syncflow.R.string.dropbox_app_key)
        val odClientId = getString(com.syncflow.R.string.onedrive_client_id)
        lifecycleScope.launch {
            val result = when (provider) {
                "dropbox" -> exchangeDropboxCode(credentialStore, code, appKey)
                "onedrive" -> exchangeOneDriveCode(credentialStore, code, odClientId)
                else -> null
            } ?: run { finish(); return@launch }
            val broadcast = Intent(OAUTH_REDIRECT_ACTION).apply {
                putExtra(OAUTH_EXTRA_TOKEN, result.first)
                putExtra(OAUTH_EXTRA_EMAIL, result.second)
                putExtra(OAUTH_EXTRA_PROVIDER, provider)
            }
            LocalBroadcastManager.getInstance(this@OAuthRedirectActivity).sendBroadcast(broadcast)
            finish()
        }
    }
}
