<?php

namespace App\Http\Controllers\Auth;

use App\Data\LoginData;
use App\Enums\KeyValue;
use App\Http\Controllers\Controller;
use App\Http\Requests\LoginRequest;
use App\Services\OraclePaymentService;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Session;
use Throwable;

class OAuthLoginController extends Controller
{
    public function __construct(
        protected OraclePaymentService $service
    ) {}

    public function index(): View
    {
        if (Session::has(KeyValue::TOKEN_API->value)) {
            Session::forget(KeyValue::TOKEN_API->value);
        }

        return view('auth.login');
    }

    public function store(LoginRequest $request): RedirectResponse
    {
        $validated = LoginData::from($request->validated());

        try {
            $response = $this->service->session(
                $validated->email,
                $validated->password
            );

            $D = [
                'cod_contribuyente' => $response->data_session->codcontri,
                'nomb' => $response->data_session->contrinomb,
                'direccion' => $response->data_session->contridirec,
                'codsesion' => $response->data_session->session,
                'codContri' => $response->data_session->codcontri,
                'Estado' => $response->data_session->logueado,
            ];

            Session::put('Datos', $D);
            Session::put('anios', $response->data_anyo);
            Session::put(KeyValue::TOKEN_API->value, $response->data_session->session);
            Session::put('Estado', $response->data_session->logueado); // logueado

            return to_route('home');
        } catch (Throwable) {
            return redirect('oauth/login')->with('alert-danger', 'Ocurrió un error durante la consulta.');
        }
    }

    public function destroy(): RedirectResponse
    {
        if (Session::has(KeyValue::TOKEN_API->value)) {
            Session::flush();
        }

        return redirect('/');
    }
}
