<?php

namespace App\Services;

use App\Enums\SerpCheckStatus;
use App\Models\SerpCheck;
use App\Serp\Data\SerpResponse;
use Illuminate\Support\Facades\DB;

final class SerpResultPersister
{
    public function __construct(private ProjectDomainMatcher $matcher) {}

    public function complete(SerpCheck $check, SerpResponse $response, array $metadata = []): void
    {
        DB::transaction(function () use ($check, $response, $metadata) {
            $locked = SerpCheck::with('keyword.project')->whereKey($check->id)->lockForUpdate()->firstOrFail();
            if ($locked->status !== SerpCheckStatus::Running) {
                return;
            }$locked->results()->delete();
            foreach ($response->results as $r) {
                $locked->results()->create(['position' => $r->position, 'result_type' => $r->resultType, 'title' => $r->title, 'url' => $r->url, 'display_url' => $r->displayUrl, 'snippet' => $r->snippet, 'is_project_domain' => $this->matcher->matches($locked->keyword->project->domain, $r->url)]);
            }$locked->complete($metadata + ['provider' => $response->providerKey, 'provider_reference' => $response->referenceId ?: $locked->provider_reference, 'result_count' => count($response->results)]);
        });
    }
}
