package com.openclaw.alfred.auth

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import com.openclaw.alfred.MainActivity

/**
 * Handles OAuth redirect callback from Authentik.
 * This activity is launched when the user completes authentication.
 */
class OAuthCallbackActivity : ComponentActivity() {
    
    private val TAG = "OAuthCallback"
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        Log.d(TAG, "OAuth callback received")
        Log.d(TAG, "Intent action: ${intent.action}")
        Log.d(TAG, "Intent data: ${intent.data}")
        Log.d(TAG, "Intent extras: ${intent.extras}")
        
        val authManager = AuthManager(this)
        
        authManager.handleAuthorizationResponse(
            intent = intent,
            onSuccess = {
                Log.d(TAG, "Login successful!")
                Toast.makeText(this, "Login successful!", Toast.LENGTH_SHORT).show()
                
                // Navigate back to MainActivity
                val mainIntent = Intent(this, MainActivity::class.java).apply {
                    flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
                }
                startActivity(mainIntent)
                finish()
            },
            onError = { error ->
                Log.e(TAG, "Login failed: $error")
                Toast.makeText(this, "Login failed: $error", Toast.LENGTH_LONG).show()
                
                // Navigate back to MainActivity (will show login screen)
                val mainIntent = Intent(this, MainActivity::class.java).apply {
                    flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK
                }
                startActivity(mainIntent)
                finish()
            }
        )
    }
}
