<?php

namespace App\Jobs;

use App\Services\Meta\MetaCustomerAudienceSyncService;
use App\Services\Customer\CustomerQualityService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

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

    public int $tries = 3;
    public int $timeout = 900;
    public int $uniqueFor = 1800;

    public function __construct(
        private readonly int $dryRunLogId,
        private readonly string $audienceKey,
        private readonly ?array $metricKeys = null,
        private readonly ?int $adminId = null,
        private readonly string $mode = 'live',
        private readonly bool $autoContinueLive = false
    ) {
    }

    public function uniqueId(): string
    {
        return implode(':', [$this->audienceKey, $this->mode, $this->dryRunLogId]);
    }

    public function middleware(): array
    {
        return [(new WithoutOverlapping('customer-quality:' . $this->audienceKey))->releaseAfter(60)->expireAfter(1200)];
    }

    public function backoff(): array
    {
        return [60, 300, 900];
    }

    public function handle(
        MetaCustomerAudienceSyncService $metaCustomerAudienceSyncService,
        CustomerQualityService $customerQualityService
    ): void
    {
        if ($this->mode === 'test_upload') {
            $log = $metaCustomerAudienceSyncService->testUploadFromDryRun(
                dryRunLogId: $this->dryRunLogId,
                audienceKey: $this->audienceKey,
                metricKeys: $this->metricKeys,
                adminId: $this->adminId
            );

            if ($this->autoContinueLive
                && $log->status === 'test_passed'
                && data_get($customerQualityService->settings(), 'auto_sync_enabled', false)
            ) {
                self::dispatch(
                    $this->dryRunLogId,
                    $this->audienceKey,
                    $this->metricKeys,
                    $this->adminId,
                    'live',
                    false
                );
            }
            return;
        }

        $metaCustomerAudienceSyncService->syncLiveFromDryRun(
            dryRunLogId: $this->dryRunLogId,
            audienceKey: $this->audienceKey,
            metricKeys: $this->metricKeys,
            adminId: $this->adminId
        );
    }
}
