<?php

namespace App\Console\Commands;

use App\Services\NotificationService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class CheckMaintenanceSchedules extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'maintenance:check-schedules';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check maintenance schedules and send notifications for upcoming and overdue maintenance';

    /**
     * The notification service instance.
     *
     * @var \App\Services\NotificationService
     */
    protected $notificationService;

    /**
     * Create a new command instance.
     *
     * @param  \App\Services\NotificationService  $notificationService
     * @return void
     */
    public function __construct(NotificationService $notificationService)
    {
        parent::__construct();
        $this->notificationService = $notificationService;
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('Checking maintenance schedules...');

        try {
            // Check upcoming maintenance schedules (7 days in advance)
            $upcomingCount = $this->notificationService->checkUpcomingMaintenanceSchedules(7);
            $this->info("Created {$upcomingCount} notifications for upcoming maintenance schedules.");

            // Check overdue maintenance schedules
            $overdueCount = $this->notificationService->checkOverdueMaintenanceSchedules();
            $this->info("Created {$overdueCount} notifications for overdue maintenance schedules.");

            // Check expiring contracts (30 days in advance)
            $contractCount = $this->notificationService->checkExpiringContracts(30);
            $this->info("Created {$contractCount} notifications for expiring contracts.");

            // Send all pending notifications
            $sentCount = $this->notificationService->sendPendingNotifications();
            $this->info("Sent {$sentCount} pending notifications.");

            $this->info('Maintenance schedule check completed successfully.');
            return 0;
        } catch (\Exception $e) {
            $this->error('An error occurred: ' . $e->getMessage());
            Log::error('Maintenance schedule check failed: ' . $e->getMessage());
            return 1;
        }
    }
}
