<?php

namespace App\Services\Auth;

use App\Models\User;
use App\Models\UserApiKey;
use Carbon\Carbon;
use Illuminate\Http\Request;

class ApiKeyService
{
    public function parseKey(Request $request): string
    {
        $auth = trim((string) $request->header('Authorization', ''));
        if (str_starts_with($auth, 'Bearer ')) {
            return trim(substr($auth, 7));
        }

        return trim((string) $request->header('X-Api-Key', ''));
    }

    public function hashKey(string $key): string
    {
        return hash('sha256', $key);
    }

    public function prefix(string $key): string
    {
        return substr($key, 0, 8);
    }

    public function resolveUser(Request $request): ?User
    {
        $key = $this->parseKey($request);
        if ($key === '') {
            return null;
        }

        $record = UserApiKey::where('key_hash', $this->hashKey($key))
            ->whereNull('revoked_at')
            ->first();

        if (! $record) {
            return null;
        }

        $record->last_used_at = Carbon::now();
        $record->save();

        $user = $record->user;
        if (! $user || (string) $user->tier !== 'personal') {
            return null;
        }

        return $user;
    }

    public function issueKey(User $user, ?string $name = null): array
    {
        $plain = 'dew_'.bin2hex(random_bytes(16));
        $hash = $this->hashKey($plain);
        $prefix = $this->prefix($plain);

        $record = UserApiKey::create([
            'user_id' => $user->id,
            'key_hash' => $hash,
            'key_prefix' => $prefix,
            'name' => $name,
        ]);

        return [
            'plain' => $plain,
            'record' => $record,
        ];
    }
}
