<?php

namespace App\Console\Commands;

use App\Models\DeviceToken;
use App\Models\User;
use App\Notifications\TestFcmNotification;
use App\Support\FirebaseCredentials;
use Illuminate\Console\Command;

class TestFcmCommand extends Command
{
    protected $signature = 'fcm:test {user_id : User ID to send a test push notification to}';

    protected $description = 'Send a test FCM push to all device tokens registered for a user';

    public function handle(): int
    {
        $userId = (int) $this->argument('user_id');
        $user = User::withoutGlobalScopes()->find($userId);

        if (! $user) {
            $this->error("User {$userId} not found.");

            return self::FAILURE;
        }

        $credentials = FirebaseCredentials::path();
        if ($credentials === null) {
            $this->error('FIREBASE_CREDENTIALS is missing or points to a file that does not exist.');
            $this->line('Expected: storage/app/firebase/kiyohr-service-account.json (exact filename on Linux).');
            $this->line('Legacy filename Kiyohr-service-account.json is also accepted.');

            return self::FAILURE;
        }

        $this->line("Using credentials: {$credentials}");

        $tokenCount = DeviceToken::query()->where('user_id', $user->id)->count();
        if ($tokenCount === 0) {
            $this->error("User {$user->id} ({$user->email}) has no rows in device_tokens.");
            $this->line('Log in on the mobile app, grant notification permission, then retry.');

            return self::FAILURE;
        }

        $this->info("Sending test FCM to {$tokenCount} device token(s) for user {$user->id} ({$user->email})...");

        $user->notify(new TestFcmNotification());

        $this->info('Test notification dispatched (runs immediately in console via AfterResponse).');
        $this->line('Check storage/logs/laravel.log for FCM multicast results. Do not run queue:work for HRMS notifications.');

        return self::SUCCESS;
    }
}
