<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\Collection;
use App\Models\CollectionMergeAction;
use App\Models\User;
use Illuminate\Validation\ValidationException;

class CollectionCanonicalService
{
    public function designate(Collection $source, Collection $target, ?User $actor = null): Collection
    {
        if ((int) $source->id === (int) $target->id) {
            throw ValidationException::withMessages([
                'target_collection_id' => 'A collection cannot canonicalize to itself.',
            ]);
        }

        $source->forceFill([
            'canonical_collection_id' => $target->id,
            'health_state' => Collection::HEALTH_MERGE_CANDIDATE,
            'placement_eligibility' => false,
        ])->save();

        CollectionMergeAction::query()->create([
            'source_collection_id' => $source->id,
            'target_collection_id' => $target->id,
            'action_type' => 'approved',
            'actor_user_id' => $actor?->id,
            'summary' => 'Canonical target designated.',
        ]);

        app(CollectionHistoryService::class)->record(
            $source->fresh(),
            $actor,
            'canonicalized',
            'Collection canonical target designated.',
            null,
            ['canonical_collection_id' => (int) $target->id]
        );

        return $source->fresh();
    }
}