<?php

namespace App\Components\Report;

use App\Models\History;
use App\Models\User\User;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Carbon;
use Livewire\Component;
use Livewire\WithPagination;

class SystemChangesReport extends Component {
    use AuthorizesRequests, WithPagination;

    public int $perPage = 50;
    public string $search = '';
    public ?int $userId = null;
    public string $category = '';
    public ?string $from = null;
    public ?string $to = null;

    public array $categories = [
        'user'       => ['label' => 'Users',       'patterns' => ['user', 'password']],
        'role'       => ['label' => 'Roles',       'patterns' => ['role']],
        'permission' => ['label' => 'Permissions', 'patterns' => ['permission']],
        'tag'        => ['label' => 'Tags',        'patterns' => ['Tag']],
        'status'     => ['label' => 'Statuses',    'patterns' => ['Status', 'status']],
        'key-date'   => ['label' => 'Key Dates',   'patterns' => ['Key Date']],
        'doc-type'   => ['label' => 'Doc Types',   'patterns' => ['Document Type']],
        'institution'=> ['label' => 'Institution Admin', 'patterns' => ['Institution Type', 'Record Type']],
    ];

    /**
     * Per-user activity (tasks, etc.) is tracked via History on the User owner
     * but is NOT a "system change" in the administrative sense.  These
     * patterns are excluded from the report regardless of the selected
     * category so it stays focused on global/system-level changes.
     */
    protected array $excludeActionPatterns = [
        'task',
    ];

    public function mount(): void {
        $this->authorize('reports.system-changes.view');
    }

    public function updatingSearch(): void   { $this->resetPage(); }
    public function updatingUserId(): void   { $this->resetPage(); }
    public function updatingCategory(): void { $this->resetPage(); }
    public function updatingPerPage(): void  { $this->resetPage(); }
    public function updatingFrom(): void     { $this->resetPage(); }
    public function updatingTo(): void       { $this->resetPage(); }

    public function render() {
        $entries = History::query()
            ->where('owner_type', User::class)
            ->with(['user', 'owner'])
            // Always exclude per-user activity noise (tasks, etc.)
            ->where(function ($q) {
                foreach ($this->excludeActionPatterns as $pattern) {
                    $q->where('action', 'not like', "%{$pattern}%");
                }
            })
            ->when($this->search, fn($q) => $q->where('action', 'like', "%{$this->search}%"))
            ->when($this->userId, fn($q) => $q->where('user_id', $this->userId))
            ->when(isset($this->categories[$this->category]), function ($q) {
                $q->where(function ($inner) {
                    foreach ($this->categories[$this->category]['patterns'] as $pattern) {
                        $inner->orWhere('action', 'like', "%{$pattern}%");
                    }
                });
            })
            ->when($this->from, fn($q) => $q->where('created_at', '>=', Carbon::parse($this->from)->startOfDay()))
            ->when($this->to,   fn($q) => $q->where('created_at', '<=', Carbon::parse($this->to)->endOfDay()))
            ->latest('created_at')
            ->paginate($this->perPage);

        return view('components.report.system-changes-report', [
            'entries' => $entries,
            'users'   => User::orderBy('name_first')->get(),
        ]);
    }
}
