<?php

namespace App\Jobs;

use App\Services\SitemapParserService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Mtc\MercuryDataModels\ContentMigrationEntry;

class ImportSitemapJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public $timeout = 600;

    public function __construct(
        private string $source,
        private bool $isUrl,
        private string $cacheKey,
        private bool $clearExisting = false,
    ) {
        $this->onQueue('sync');
    }

    public function handle(SitemapParserService $parser): void
    {
        Cache::put($this->cacheKey, [
            'status' => 'processing',
            'processed' => 0,
            'imported' => 0,
            'total' => 0,
        ], now()->addMinutes(30));

        if ($this->clearExisting) {
            ContentMigrationEntry::query()->delete();
        }

        try {
            if ($this->isUrl) {
                $urls = $parser->fetchAndParse($this->source);
            } else {
                $xmlContent = Storage::disk('local')->get($this->source);
                $urls = $parser->parse($xmlContent);
                Storage::disk('local')->delete($this->source);
            }
        } catch (\Exception $e) {
            Cache::put($this->cacheKey, [
                'status' => 'failed',
                'error' => $e->getMessage(),
            ], now()->addMinutes(30));

            return;
        }

        $existingUrls = ContentMigrationEntry::pluck('original_url')
            ->map(fn ($url) => rtrim($url, '/'))
            ->toArray();

        $imported = 0;
        $total = count($urls);

        foreach ($urls as $i => $url) {
            $normalised = rtrim($url, '/');

            if (!in_array($normalised, $existingUrls)) {
                ContentMigrationEntry::create(['original_url' => $url]);
                $existingUrls[] = $normalised;
                $imported++;
            }

            if (($i + 1) % 10 === 0) {
                Cache::put($this->cacheKey, [
                    'status' => 'processing',
                    'processed' => $i + 1,
                    'imported' => $imported,
                    'total' => $total,
                ], now()->addMinutes(30));
            }
        }

        Cache::put($this->cacheKey, [
            'status' => 'complete',
            'processed' => $total,
            'imported' => $imported,
            'total' => $total,
        ], now()->addMinutes(30));
    }

    public function failed(\Throwable $exception): void
    {
        Cache::put($this->cacheKey, [
            'status' => 'failed',
            'error' => $exception->getMessage(),
        ], now()->addMinutes(30));
    }
}
