<?php

namespace App\Console\Commands;

use App\Jobs\SyncMetaAdsInsightsJob;
use App\Services\Meta\MetaAdsInsightsSyncService;
use App\Services\Meta\MetaAdsPerformanceService;
use App\Services\Meta\MetaAdsProductRuleService;
use App\Services\Meta\MetaCampaignSafetyAuditService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Http\Request;

class MetaAdsInsightsSyncCommand extends Command
{
    protected $signature = 'meta-ads:sync-insights
        {--from= : Start date in Y-m-d format}
        {--to= : End date in Y-m-d format}
        {--days=7 : Number of days when --from is omitted}
        {--run-now : Run synchronously instead of dispatching a queue job}';

    protected $description = 'Sync Meta campaign, ad set, ad and catalog product performance.';

    public function handle(
        MetaAdsInsightsSyncService $service,
        MetaAdsPerformanceService $performanceService,
        MetaAdsProductRuleService $productRuleService,
        MetaCampaignSafetyAuditService $campaignSafetyAuditService
    ): int {
        try {
            $to = $this->option('to')
                ? Carbon::parse((string) $this->option('to'))->endOfDay()
                : now()->endOfDay();
            $from = $this->option('from')
                ? Carbon::parse((string) $this->option('from'))->startOfDay()
                : $to->copy()->subDays(max(1, (int) $this->option('days')) - 1)->startOfDay();

            if ($this->option('run-now')) {
                $log = $service->sync($from, $to);
                $report = $performanceService->report(Request::create('/', 'GET', [
                    'from' => $from->toDateString(),
                    'to' => $to->toDateString(),
                ]));
                $ruleSummary = $productRuleService->evaluate($report['product_rows']);
                $audit = $campaignSafetyAuditService->audit();

                $this->info(sprintf(
                    'Meta Ads Insights sync %s. Base rows: %d, Product rows: %d.',
                    $log->status,
                    $log->base_rows,
                    $log->product_rows
                ));
                $this->info('Product rules evaluated: ' . $this->formatSummary($ruleSummary) . '.');
                $this->info(sprintf(
                    'Campaign safety audit %s. Risk missing: %d, Purchaser missing: %d.',
                    $audit->status,
                    (int) $audit->risk_missing_count,
                    max(0, (int) $audit->total_adsets - (int) $audit->purchaser_excluded_count)
                ));

                return self::SUCCESS;
            }

            if (config('queue.default') === 'sync') {
                $this->error('Meta Ads Insights sync requires an asynchronous queue driver.');

                return self::FAILURE;
            }

            SyncMetaAdsInsightsJob::dispatch($from->toDateString(), $to->toDateString());
            $this->info("Meta Ads Insights sync queued for {$from->toDateString()} through {$to->toDateString()}.");

            return self::SUCCESS;
        } catch (\Throwable $exception) {
            report($exception);
            $this->error($exception->getMessage());

            return self::FAILURE;
        }
    }

    private function formatSummary(array $summary): string
    {
        return collect($summary)
            ->map(fn ($value, string $key) => $key . '=' . $value)
            ->implode(', ');
    }
}
