<?php

namespace App\Console\Commands;

use App\Models\Company;
use App\Models\PerformanceReview;
use App\Models\User;
use App\Notifications\LeaveBalanceLowNotification;
use App\Notifications\PerformanceReviewDueNotification;
use App\Services\HrmsNotificationService;
use App\Services\Leave\LeaveLedgerService;
use Illuminate\Console\Command;

class SendProactiveHrAlerts extends Command
{
    protected $signature = 'hrms:send-proactive-alerts {company_id? : Optional company ID}';

    protected $description = 'Send low leave balance and due performance review alerts';

    public function handle(HrmsNotificationService $notifier, LeaveLedgerService $ledger): int
    {
        $companyId = $this->argument('company_id') ? (int) $this->argument('company_id') : null;
        $companies = $companyId
            ? Company::withoutGlobalScopes()->where('id', $companyId)->get()
            : Company::withoutGlobalScopes()->where('status', 'active')->get();

        $year = $ledger->leaveYear();
        $leaveAlerts = 0;
        $reviewAlerts = 0;

        foreach ($companies as $company) {
            $users = User::query()
                ->where('company_id', $company->id)
                ->forActiveDirectory()
                ->get();

            foreach ($users as $user) {
                $balances = $ledger->balancesForUser($user, $year);
                foreach ($balances as $row) {
                    if (! empty($row['is_unlimited'])) {
                        continue;
                    }
                    $available = (float) ($row['available'] ?? 0);
                    if ($available > 0 && $available <= 1) {
                        $user->notify(new LeaveBalanceLowNotification($user, (string) ($row['name'] ?? 'Leave'), $available));
                        $leaveAlerts++;
                    }
                }
            }

            $dueReviews = PerformanceReview::with(['user', 'reviewer', 'performanceCycle'])
                ->where('company_id', $company->id)
                ->where('status', 'pending')
                ->where(function ($q) {
                    $q->whereNull('review_date')->orWhere('review_date', '<=', now()->toDateString());
                })
                ->get();

            foreach ($dueReviews as $review) {
                if ($review->reviewer) {
                    $review->reviewer->notify(new PerformanceReviewDueNotification($review));
                    $reviewAlerts++;
                }
            }
        }

        $this->info("Sent {$leaveAlerts} leave balance alert(s) and {$reviewAlerts} performance review alert(s).");

        return self::SUCCESS;
    }
}
