<?php

namespace App\Modules\AntiTheft\Domain;

use DateTimeImmutable;
use DateTimeZone;
use InvalidArgumentException;

final readonly class RuleSchedule
{
    /**
     * @param array<int, int> $weekdays ISO-8601 weekdays, Monday=1 through Sunday=7.
     */
    public function __construct(
        public array $weekdays = [1, 2, 3, 4, 5, 6, 7],
        public string $startsAt = '00:00',
        public string $endsAt = '23:59',
        public string $timezone = 'UTC',
    ) {
        if ($this->weekdays === [] || array_diff($this->weekdays, range(1, 7)) !== []) {
            throw new InvalidArgumentException('Schedule weekdays must use ISO values 1 through 7.');
        }

        if (! preg_match('/^(?:[01]\d|2[0-3]):[0-5]\d$/', $this->startsAt)
            || ! preg_match('/^(?:[01]\d|2[0-3]):[0-5]\d$/', $this->endsAt)) {
            throw new InvalidArgumentException('Schedule times must use 24-hour HH:MM format.');
        }

        new DateTimeZone($this->timezone);
    }

    public function isActiveAt(DateTimeImmutable $instant): bool
    {
        $local = $instant->setTimezone(new DateTimeZone($this->timezone));
        if (! in_array((int) $local->format('N'), $this->weekdays, true)) {
            return false;
        }

        $time = $local->format('H:i');
        if ($this->startsAt <= $this->endsAt) {
            return $time >= $this->startsAt && $time <= $this->endsAt;
        }

        return $time >= $this->startsAt || $time <= $this->endsAt;
    }
}
