<?php

namespace App\Http\Controllers;

use App\Support\ApiTokenPermissionMatrix;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Validation\ValidationException;
use Laravel\Sanctum\PersonalAccessToken;

class ProfileApiTokenController extends Controller
{
    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'expires_at' => ['nullable', 'date', 'after_or_equal:today'],
            'permissions' => ['required', 'array'],
        ], [
            'permissions.required' => 'Select at least one right for the API key.',
        ]);

        $abilities = ApiTokenPermissionMatrix::abilitiesFromInput($validated['permissions']);

        if ($abilities === []) {
            throw ValidationException::withMessages([
                'permissions' => 'Select at least one right for the API key.',
            ]);
        }

        $expiresAt = null;
        if (! empty($validated['expires_at'])) {
            $expiresAt = Carbon::parse((string) $validated['expires_at'])->endOfDay();
        }

        $token = $request->user()->createToken(
            (string) $validated['name'],
            $abilities,
            $expiresAt
        );

        return back()
            ->with('success', 'API the key has been released.')
            ->with('api_token_plain_text', $token->plainTextToken);
    }

    public function destroy(Request $request, PersonalAccessToken $token): RedirectResponse
    {
        if ((int) $token->tokenable_id !== (int) $request->user()->id || $token->tokenable_type !== $request->user()::class) {
            abort(403);
        }

        $token->delete();

        return back()->with('success', 'API key revoked.');
    }
}
