<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Http\Controllers\RecurringAppointmentController;

class ProcessRecurringAppointments extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'appointments:process-recurring';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Procesa las citas recurrentes: envía recordatorios y crea citas automáticas';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $this->info('Procesando citas recurrentes...');
        
        try {
            $controller = new RecurringAppointmentController();
            $result = $controller->processPendingRecurringAppointments();
            
            $data = json_decode($result->getContent(), true);
            
            if (isset($data['success']) && $data['success']) {
                $this->info('Citas recurrentes procesadas exitosamente.');
                return 0;
            } else {
                $this->error('Error al procesar citas recurrentes: ' . ($data['message'] ?? 'Error desconocido'));
                return 1;
            }
        } catch (\Throwable $th) {
            $this->error('Error al procesar citas recurrentes: ' . $th->getMessage());
            return 1;
        }
    }
}
