<?php

namespace App\Support;

use App\Models\EventJoinToken;
use App\Models\TaskCollection;
use App\Models\Tenant;
use Filament\Facades\Filament;
use Illuminate\Support\Arr;
use Illuminate\Support\Carbon;

class TenantOnboardingState
{
    public static function tenant(?Tenant $tenant = null): ?Tenant
    {
        if ($tenant) {
            return $tenant;
        }

        /** @var Tenant|null $tenant */
        $tenant = Filament::getTenant();

        return $tenant;
    }

    public static function status(?Tenant $tenant = null): array
    {
        $tenant = self::tenant($tenant);

        if (! $tenant) {
            return [
                'packages' => false,
                'event' => false,
                'palette' => false,
                'invite' => false,
            ];
        }

        $hasCustomCollections = TaskCollection::query()
            ->where('tenant_id', $tenant->id)
            ->exists();

        $hasEvent = $tenant->events()->exists();

        $palette = Arr::get($tenant->settings ?? [], 'branding.palette');

        $hasInvite = EventJoinToken::query()
            ->whereHas('event', fn ($query) => $query->where('tenant_id', $tenant->id))
            ->exists();

        return [
            'packages' => $hasCustomCollections,
            'event' => $hasEvent,
            'palette' => filled($palette),
            'invite' => $hasInvite,
        ];
    }

    public static function completed(?Tenant $tenant = null): bool
    {
        $status = self::status($tenant);

        return collect($status)->every(fn ($done) => $done === true)
            || Arr::has(self::tenant($tenant)?->settings ?? [], 'onboarding.completed_at');
    }

    public static function markCompleted(Tenant $tenant, array $data = []): void
    {
        $settings = $tenant->settings ?? [];

        Arr::set($settings, 'onboarding.completed_at', Carbon::now()->toIso8601String());

        if (Arr::has($data, 'primary_event_id')) {
            Arr::set($settings, 'onboarding.primary_event_id', Arr::get($data, 'primary_event_id'));
        }

        if (Arr::has($data, 'selected_packages')) {
            Arr::set($settings, 'onboarding.selected_packages', Arr::get($data, 'selected_packages'));
        }

        if (Arr::has($data, 'qr_layout')) {
            Arr::set($settings, 'onboarding.qr_layout', Arr::get($data, 'qr_layout'));
        }

        $tenant->forceFill(['settings' => $settings])->save();
    }
}
