<?php

namespace App\Modules\HR\EmployeeSelfService\Services;

use App\Models\User;
use App\Modules\Dashboard\Services\NotificationCenterService;
use App\Modules\HR\Attendance\Repositories\AttendanceExceptionRepository;
use App\Modules\HR\Attendance\Repositories\AttendanceRecordRepository;
use App\Modules\HR\Leave\Models\LeaveRequest;
use App\Modules\HR\Leave\Support\LeaveRequestStatus;
use Carbon\CarbonImmutable;

class EmployeeSelfDashboardService
{
    public function __construct(
        private readonly SelfEmployeeContextService $context,
        private readonly AttendanceRecordRepository $attendance,
        private readonly AttendanceExceptionRepository $exceptions,
        private readonly NotificationCenterService $notifications,
    ) {}

    /**
     * @return array{month: array<string, mixed>, pending_leave: int, unread_notifications: int, attendance_issues: int}
     */
    public function widgets(User $user): array
    {
        $e = $this->context->employee();
        $tid = (int) $e->tenant_id;
        $month = CarbonImmutable::now()->startOfMonth();
        $agg = $this->attendance->monthlyAggregatesForEmployee($tid, (int) $e->id, $month);
        $pendingLeave = LeaveRequest::query()
            ->where('tenant_id', $tid)
            ->where('employee_id', $e->id)
            ->whereIn('status', [LeaveRequestStatus::PENDING, LeaveRequestStatus::MANAGER_APPROVED])
            ->count();

        return [
            'month' => $agg,
            'pending_leave' => $pendingLeave,
            'unread_notifications' => $this->notifications->unreadCount($user),
            'attendance_issues' => $this->exceptions->pendingCountForEmployee($tid, (int) $e->id),
        ];
    }
}
