<?php

namespace App\Modules\Pilkades\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Modules\Pilkades\Services\ActivityLogService;
use App\Modules\Pilkades\Support\ApiAbility;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class ApiTokenController extends Controller
{
    public function __construct(protected ActivityLogService $activityLog) {}

    public function index(): View
    {
        $tokens = Auth::user()->tokens()->latest()->get();
        $abilityLabels = ApiAbility::labels();

        return view('pilkades::super-admin.api-tokens.index', compact('tokens', 'abilityLabels'));
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'abilities' => ['required', 'array', 'min:1'],
            'abilities.*' => [Rule::in(ApiAbility::all())],
            'expires_in_days' => ['nullable', 'integer', 'min:1', 'max:365'],
        ]);

        $expiresAt = ! empty($data['expires_in_days'])
            ? now()->addDays((int) $data['expires_in_days'])
            : null;

        $token = Auth::user()->createToken($data['name'], $data['abilities'], $expiresAt);

        $this->activityLog->log(Auth::user(), 'api-token.created', properties: ['name' => $data['name'], 'abilities' => $data['abilities']]);

        return redirect()->route('super-admin.api-tokens.index')
            ->with('plainTextToken', $token->plainTextToken)
            ->with('success', 'Token API berhasil dibuat. Salin sekarang — token tidak akan ditampilkan lagi.');
    }

    public function destroy(string $tokenId): RedirectResponse
    {
        $token = Auth::user()->tokens()->where('id', $tokenId)->firstOrFail();
        $token->delete();

        $this->activityLog->log(Auth::user(), 'api-token.revoked', properties: ['name' => $token->name]);

        return back()->with('success', 'Token API berhasil dicabut.');
    }
}
