<?php

namespace App\Models;

use CodeIgniter\Model;

class ApiKeyModel extends Model
{
    protected $table         = 'api_keys';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $allowedFields = [
        'organization_id',
        'created_by_user_id',
        'name',
        'key_prefix',
        'key_hash',
        'scopes',
        'status',
        'last_used_at',
        'expires_at',
    ];

    public function findActiveByHash(string $hash): ?array
    {
        $record = $this->where('key_hash', $hash)
            ->where('status', 'active')
            ->first();

        if (! $record) {
            return null;
        }

        if (! empty($record['expires_at']) && strtotime((string) $record['expires_at']) < time()) {
            return null;
        }

        $record['scope_list'] = $this->decodeScopes($record['scopes'] ?? '[]');

        return $record;
    }

    public function forOrganization(int $organizationId): array
    {
        $records = $this->where('organization_id', $organizationId)
            ->orderBy('created_at', 'DESC')
            ->findAll();

        foreach ($records as &$record) {
            $record['scope_list'] = $this->decodeScopes($record['scopes'] ?? '[]');
        }

        return $records;
    }

    private function decodeScopes(string $scopes): array
    {
        $decoded = json_decode($scopes, true);

        return is_array($decoded) ? array_values(array_unique(array_filter($decoded, 'is_string'))) : [];
    }
}
