<?php

namespace App\Jobs;

use App\Services\Meta\MetaAdsInsightsSyncService;
use App\Services\Meta\MetaAdsPerformanceService;
use App\Services\Meta\MetaAdsProductRuleService;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Http\Request;

class SyncMetaAdsInsightsJob implements ShouldQueue, ShouldBeUnique
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public int $tries = 2;
    public int $timeout = 900;
    public int $uniqueFor = 3600;

    public function __construct(
        private readonly string $from,
        private readonly string $to
    ) {
    }

    public function handle(
        MetaAdsInsightsSyncService $service,
        MetaAdsPerformanceService $performanceService,
        MetaAdsProductRuleService $productRuleService
    ): void {
        $from = Carbon::parse($this->from)->startOfDay();
        $to = Carbon::parse($this->to)->endOfDay();
        $service->sync($from, $to);

        $report = $performanceService->report(Request::create('/', 'GET', [
            'from' => $from->toDateString(),
            'to' => $to->toDateString(),
        ]));
        $productRuleService->evaluate($report['product_rows']);
        AuditMetaCampaignSafetyJob::dispatch();
    }

    public function uniqueId(): string
    {
        return $this->from . ':' . $this->to;
    }
}
