<?php

namespace App\Console\Commands;

use App\Services\WhatsAppService;
use Illuminate\Console\Command;

class WhatsAppTestCommand extends Command
{
    protected $signature = 'whatsapp:test {phone : Phone number in E.164 (e.g. 50688393130)}';

    protected $description = 'Send a test hello_world template to verify WhatsApp API connection';

    public function handle(): int
    {
        $phone = $this->argument('phone');

        $whatsapp = app(WhatsAppService::class);

        if (!$whatsapp->isConfigured()) {
            $this->error('WhatsApp not configured. Set WHATSAPP_TOKEN and WHATSAPP_PHONE_NUMBER_ID in .env');
            return self::FAILURE;
        }

        $this->info("Sending hello_world template to {$phone}...");

        $ok = $whatsapp->sendTemplate($phone, 'hello_world');

        if ($ok) {
            $this->info('Message sent successfully. Check WhatsApp on that number.');
            return self::SUCCESS;
        }

        $this->error('Failed to send.');
        $err = $whatsapp->getLastError();
        if ($err) {
            $this->line($err);
        }
        $this->line('Check storage/logs/laravel.log for full details.');
        return self::FAILURE;
    }
}
