<?php

namespace App\Livewire;

use App\Enums\ActivityTypeEnum;
use App\Models\ActivityLog;
use App\Services\Activity\ActivitySummary;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Builder;
use Livewire\Component;
use Livewire\WithPagination;

class Activity extends Component
{
    use WithPagination;

    public string $type = '';

    public int $days = 7;

    public function updatedType(): void
    {
        $this->resetPage();
    }

    public function updatedDays(): void
    {
        $this->resetPage();
    }

    /**
     * @return Builder<ActivityLog>
     */
    private function query(): Builder
    {
        return ActivityLog::query()
            ->withSubjectDetails()
            ->since(now()->subDays($this->days))
            ->when(
                $this->type !== '',
                fn (Builder $q) => $q->where('type', $this->type),
            )
            ->latestFirst();
    }

    public function render(ActivitySummary $summary): View
    {
        return view('livewire.activity', [
            'entries' => $this->query()->paginate(25),
            'typeOptions' => ActivityTypeEnum::options(),
            'summaryDay' => $summary->since(now()->subDay()),
            'summaryWeek' => $summary->since(now()->subWeek()),
        ])->layout('layouts.app');
    }
}
