<?php

namespace App\Console\Commands;

use App\Models\ManagedEnvironment;
use App\Services\OperationRunService;
use App\Support\OperationRunType;
use Carbon\CarbonImmutable;
use Illuminate\Console\Command;

class TenantpilotDispatchDirectoryGroupsSync extends Command
{
    protected $signature = 'tenantpilot:directory-groups:dispatch {--tenant=* : Limit to managed_environment_id/external_id}';

    protected $description = 'Dispatch scheduled directory group sync runs (idempotent per tenant minute-slot).';

    public function handle(): int
    {
        if (! (bool) config('directory_groups.schedule.enabled', false)) {
            return self::SUCCESS;
        }

        $now = CarbonImmutable::now('UTC');
        $timeUtc = (string) config('directory_groups.schedule.time_utc', '02:00');

        if (! $this->isDueAt($now, $timeUtc)) {
            return self::SUCCESS;
        }

        if (! class_exists(\App\Jobs\EntraGroupSyncJob::class)) {
            $this->warn('EntraGroupSyncJob is not available; skipping scheduled directory group sync dispatch.');

            return self::SUCCESS;
        }

        $tenantIdentifiers = array_values(array_filter(array_map('strval', array_merge(
            (array) $this->option('tenant'),
            (array) config('directory_groups.schedule.tenants', []),
        ))));

        $tenants = $this->resolveTenants($tenantIdentifiers);

        $selectionKey = 'groups-v1:all';
        $slotKey = $now->format('YmdHi').'Z';

        $created = 0;
        $skipped = 0;

        foreach ($tenants as $tenant) {
            /** @var OperationRunService $opService */
            $opService = app(OperationRunService::class);
            $opRun = $opService->ensureRunWithIdentityStrict(
                tenant: $tenant,
                type: OperationRunType::DirectoryGroupsSync->value,
                identityInputs: [
                    'selection_key' => $selectionKey,
                    'slot_key' => $slotKey,
                ],
                context: [
                    'selection_key' => $selectionKey,
                    'slot_key' => $slotKey,
                    'trigger' => 'scheduled',
                ],
                initiator: null,
            );

            if (! $opRun->wasRecentlyCreated) {
                $skipped++;

                continue;
            }

            $created++;

            dispatch(new \App\Jobs\EntraGroupSyncJob(
                tenantId: $tenant->getKey(),
                selectionKey: $selectionKey,
                slotKey: $slotKey,
                runId: null,
                operationRun: $opRun,
            ));
        }

        $this->info(sprintf(
            'Scanned %d tenant(s), created %d run(s), skipped %d duplicate run(s).',
            $tenants->count(),
            $created,
            $skipped,
        ));

        return self::SUCCESS;
    }

    /**
     * @param  array<int, string>  $tenantIdentifiers
     */
    private function resolveTenants(array $tenantIdentifiers): \Illuminate\Support\Collection
    {
        $query = ManagedEnvironment::activeQuery();

        if ($tenantIdentifiers !== []) {
            $query->where(function ($subQuery) use ($tenantIdentifiers) {
                foreach ($tenantIdentifiers as $identifier) {
                    if (ctype_digit($identifier)) {
                        $subQuery->orWhereKey((int) $identifier);

                        continue;
                    }

                    $subQuery->orWhere('slug', $identifier);
                }
            });
        }

        return $query->get();
    }

    private function isDueAt(CarbonImmutable $now, string $timeUtc): bool
    {
        if (! preg_match('/^(?<hour>[01]\\d|2[0-3]):(?<minute>[0-5]\\d)$/', $timeUtc, $matches)) {
            return false;
        }

        return (int) $matches['hour'] === (int) $now->format('H')
            && (int) $matches['minute'] === (int) $now->format('i');
    }
}
