<?php

namespace App\Console\Commands;

use App\Jobs\SyncCustomerQualityAudienceJob;
use App\Services\Customer\CustomerQualityService;
use App\Services\Meta\MetaCustomerAudienceSyncService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class CustomerQualityAutoSyncCommand extends Command
{
    protected $signature = 'customer-quality:auto-sync';

    protected $description = 'Refresh metrics, create dry runs, then queue test-cleanup and live Meta sync jobs when auto sync is enabled.';

    public function __construct(
        private readonly CustomerQualityService $customerQualityService,
        private readonly MetaCustomerAudienceSyncService $metaAudienceSyncService
    ) {
        parent::__construct();
    }

    public function handle(): int
    {
        if (! data_get($this->customerQualityService->settings(), 'auto_sync_enabled', false)) {
            $this->info('Customer Quality auto sync is disabled.');

            return self::SUCCESS;
        }

        if (config('queue.default') === 'sync') {
            $this->error('Customer Quality auto sync requires an asynchronous queue driver.');

            return self::FAILURE;
        }

        $metaWriteEligibility = $this->customerQualityService->metaWriteEligibility();
        if (! data_get($metaWriteEligibility, 'allowed', false)) {
            $this->error(
                'Customer Quality auto sync safety prerequisites are not satisfied. '
                .implode(' ', (array) data_get($metaWriteEligibility, 'reasons', []))
            );

            return self::FAILURE;
        }

        $lock = Cache::lock('customer-quality:auto-sync', 3600);
        if (! $lock->get()) {
            $this->error('Another Customer Quality sync is already running.');

            return self::FAILURE;
        }

        try {

            $result = $this->customerQualityService->refreshMetrics();
            $this->info(sprintf(
                'Metrics refreshed: %d; high quality: %d; risk: %d.',
                $result['metric_count'],
                $result['high_quality_count'],
                $result['risk_count']
            ));

            foreach (array_keys(CustomerQualityService::AUDIENCE_NAMES) as $audienceKey) {
                $dryRun = $this->metaAudienceSyncService->dryRun($audienceKey);
                SyncCustomerQualityAudienceJob::dispatch(
                    $dryRun->id,
                    $audienceKey,
                    null,
                    null,
                    'test_upload',
                    true
                );

                $this->info(sprintf(
                    '%s auto pipeline queued. Eligible: %d; add: %d; remove: %d; checksum: %s.',
                    CustomerQualityService::AUDIENCE_NAMES[$audienceKey],
                    $dryRun->eligible_count,
                    $dryRun->add_count,
                    $dryRun->remove_count,
                    $dryRun->checksum
                ));
            }

            return self::SUCCESS;
        } finally {
            $lock->release();
        }
    }
}
