<?php

namespace App\Console\Commands;

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

class CloudflareCacheClear extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cloudflare:clear-cache';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Clear Cloudflare cache for a tenant';

    public function __construct(private readonly CloudflareService $service)
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        if (!tenant()->has_cloudflare) {
            $this->output->error('Site does not have cloudflare enabled');
            return self::FAILURE;
        }

        $response = $this->service->clear(tenant());
        $response->successful() && $response->json('success')
            ? $this->output->success('Cache cleared')
            : $this->output->error(collect($response->json('errors'))->pluck('message')->toArray());

        return $response->successful() && $response->json('success');
    }
}
