<?php

declare(strict_types=1);

namespace App\Domain\Allowlist;

use App\Domain\Ip\Cidr;
use App\Domain\Ip\IpAddress;
use DateTimeImmutable;

/**
 * One never-block entry. Same shape as ManualBlock minus `expires_at` —
 * allowlist entries don't expire on a clock; they're removed by an
 * administrator. Per SPEC §5 allowlist always wins over manual blocks.
 */
final class AllowlistEntry
{
    public const KIND_IP = 'ip';
    public const KIND_SUBNET = 'subnet';

    public function __construct(
        public readonly int $id,
        public readonly string $kind,
        public readonly ?IpAddress $ip,
        public readonly ?Cidr $cidr,
        public readonly ?string $reason,
        public readonly DateTimeImmutable $createdAt,
        public readonly ?int $createdByUserId,
    ) {
    }

    /**
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        $base = [
            'id' => $this->id,
            'kind' => $this->kind,
            'reason' => $this->reason,
            'created_at' => $this->createdAt->format('Y-m-d\TH:i:s\Z'),
            'created_by_user_id' => $this->createdByUserId,
        ];

        if ($this->kind === self::KIND_IP) {
            $base['ip'] = $this->ip?->text();
            $base['cidr'] = null;
            $base['prefix_length'] = null;
        } else {
            $base['ip'] = null;
            $base['cidr'] = $this->cidr?->text();
            $base['prefix_length'] = $this->cidr?->originalPrefix();
        }

        return $base;
    }
}
