<?php

namespace App\Modules\HR\Recruitment\Services;

use App\Models\User;
use App\Modules\HR\Recruitment\Models\RecruitmentOnboardingCase;
use App\Modules\HR\Recruitment\Repositories\RecruitmentOnboardingCaseRepository;
use App\Modules\HR\Recruitment\Support\OnboardingSection;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class OnboardingWorkspacePageService
{
    public function __construct(
        private readonly RecruitmentOnboardingCaseRepository $cases,
        private readonly OnboardingDocumentService $documents,
    ) {}

    /**
     * @param  array{q?: ?string, status?: ?string}  $filters
     */
    public function index(int $tenantId, array $filters): LengthAwarePaginator
    {
        return $this->cases->paginateForTenant($tenantId, $filters);
    }

    /** @return array<string, mixed> */
    public function workspace(int $tenantId, RecruitmentOnboardingCase $case, string $tab): array
    {
        $row = $this->cases->findWorkspace($tenantId, (int) $case->id);
        abort_if($row === null, 404);
        $tab = in_array($tab, $this->tabs(), true) ? $tab : 'checklist';

        return [
            'case' => $row,
            'tab' => $tab,
            'tabs' => $this->tabs(),
            'sectionTasks' => $row->tasks
                ->where('section', $tab)
                ->sortBy('sort_order')
                ->values(),
            'sectionCounts' => $this->sectionCounts($row),
            'employeeDocuments' => $tab === OnboardingSection::DOCUMENTS
                ? $this->documents->listForEmployee($row->employee)
                : collect(),
            'assignees' => User::query()
                ->where('tenant_id', $tenantId)
                ->orderBy('name')
                ->limit(200)
                ->get(['id', 'name']),
        ];
    }

    /** @return list<string> */
    public function tabs(): array
    {
        return OnboardingSection::all();
    }

    /** @return array<string, array{total: int, done: int}> */
    private function sectionCounts(RecruitmentOnboardingCase $case): array
    {
        $counts = [];
        foreach (OnboardingSection::all() as $section) {
            $tasks = $case->tasks->where('section', $section);
            $done = $tasks->filter(
                fn ($t) => in_array((string) $t->status, ['completed', 'skipped'], true)
            )->count();
            $counts[$section] = ['total' => $tasks->count(), 'done' => $done];
        }

        return $counts;
    }
}
