<?php

namespace App\Livewire\Issues;

use App\Models\Issue;
use App\Models\Project;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Layout;
use Livewire\Attributes\On;
use Livewire\Component;

#[Layout('layouts.app')]
class IssueManager extends Component
{
    public Project $project;

    public function mount(Project $project)
    {
        $this->project = $project;
        abort_unless($this->canAccessProject() && Auth::user()->can('view issues'), 403);
    }

    /** The current user must be a project member (or super-admin) to touch issues. */
    private function canAccessProject(): bool
    {
        $user = Auth::user();

        return $user->can('manage all')
            || $this->project->users()->where('user_id', $user->id)->exists();
    }

    /** Re-render the stats bar after the embedded table changes an issue. */
    #[On('issuesChanged')]
    public function refreshStats(): void
    {
        // No state to mutate — the listener simply triggers a re-render so the
        // stat counters recompute from the database in render().
    }

    public function render()
    {
        $counts = Issue::where('project_id', $this->project->id)
            ->selectRaw('status, count(*) as c')
            ->groupBy('status')
            ->pluck('c', 'status');

        return view('livewire.issues.issue-manager', [
            'countOpen' => (int) ($counts['open'] ?? 0),
            'countInReview' => (int) ($counts['in_review'] ?? 0),
            'countResolved' => (int) ($counts['resolved'] ?? 0),
            'countClosed' => (int) ($counts['closed'] ?? 0),
            'countTotal' => (int) $counts->sum(),
        ]);
    }
}
