<?php

namespace App\Services\Calendar;

use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;

class CalendarSettingsPersister
{
    public function defaults(User $user, string $tz): array
    {
        $defaultView    = $user->getSetting('calendar.last_view', 'month');
        $defaultDate    = $user->getSetting('calendar.last_date', Carbon::today($tz)->toDateString());
        $defaultDensity = (int) $user->getSetting('calendar.last_density', 30);
        $defaultDaytimeHours = (int) $user->getSetting('calendar.daytime_hours', 0);

        $weekStartPref = $user->getSetting('calendar.week_start', 'sunday');
        $weekStartPref = in_array($weekStartPref, ['sunday', 'monday'], true)
            ? $weekStartPref
            : 'sunday';
        $weekStart = $weekStartPref === 'monday' ? Carbon::MONDAY : Carbon::SUNDAY;
        $weekEnd = (int) (($weekStart + 6) % 7);

        return [
            'view'            => $defaultView,
            'date'            => $defaultDate,
            'density'         => $defaultDensity,
            'daytime_hours'   => $defaultDaytimeHours,
            'week_start_pref' => $weekStartPref,
            'week_start'      => $weekStart,
            'week_end'        => $weekEnd,
        ];
    }

    public function resolveDensity(Request $request, int $defaultDensity): array
    {
        $stepMinutes = (int) $request->query('density', $defaultDensity);
        if (!in_array($stepMinutes, [15, 30, 60], true)) {
            $stepMinutes = 30;
        }

        $labelEvery = match ($stepMinutes) {
            15 => 1,
            30 => 2,
            60 => 4,
        };

        return [
            'step' => $stepMinutes,
            'label_every' => $labelEvery,
        ];
    }

    public function resolveDaytimeHours(Request $request, int $defaultDaytimeHours): bool
    {
        return (int) $request->query('daytime_hours', $defaultDaytimeHours) === 1;
    }

    public function daytimeHoursRange(): array
    {
        return ['start' => 8, 'end' => 18];
    }

    public function persist(
        User $user,
        Request $request,
        string $view,
        Carbon $rangeStart,
        int $stepMinutes,
        bool $daytimeHoursEnabled
    ): void {
        if ($request->hasAny(['view', 'date', 'density'])) {
            $user->setSetting('calendar.last_view', $view);
            $user->setSetting('calendar.last_date', $rangeStart->toDateString());
            $user->setSetting('calendar.last_density', (string) $stepMinutes);
        }

        if ($request->has('daytime_hours')) {
            $user->setSetting('calendar.daytime_hours', $daytimeHoursEnabled ? '1' : '0');
        }
    }
}
