<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use WorkOS\UserManagement;
use WorkOS\WorkOS;

class WorkosController extends Controller
{
    private function bootWorkOS(): void
    {
        WorkOS::setApiKey(config('services.workos.api_key'));
        WorkOS::setClientId(config('services.workos.client_id'));
    }

    public function redirect(Request $request): RedirectResponse
    {
        $this->bootWorkOS();

        $userManagement = new UserManagement();

        $redirectUri = route('workos.callback');

        $state = [
            'return_to' => url('/'),
        ];

        $authorizationUrl = $userManagement->getAuthorizationUrl(
            $redirectUri,
            $state,
            UserManagement::AUTHORIZATION_PROVIDER_GOOGLE_OAUTH
        );

        return redirect()->away($authorizationUrl);
    }

    public function callback(Request $request): RedirectResponse
    {
        $this->bootWorkOS();

        $code = (string) $request->query('code');
        if ($code === '') {
            abort(400, 'Missing code');
        }

        $userManagement = new UserManagement();

        $auth = $userManagement->authenticateWithCode(
            config('services.workos.client_id'),
            $code,
            $request->ip(),
            $request->userAgent()
        );

        $workosUser = $auth->user;

        $name = trim(($workosUser->firstName ?? '') . ' ' . ($workosUser->lastName ?? ''));
        if ($name === '') {
            $name = $workosUser->email;
        }

        $user = User::updateOrCreate(
            ['email' => $workosUser->email],
            [
                'name' => $name,
                'workos_user_id' => $workosUser->id,
            ]
        );

        Auth::login($user, true);

        $stateRaw = $request->query('state');
        $state = is_string($stateRaw) ? json_decode($stateRaw, true) : null;
        $returnTo = is_array($state) && isset($state['return_to']) ? $state['return_to'] : url('/');

        return redirect()->to($returnTo);
    }
}
