<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\Collection;
use App\Models\User;

class CollectionExperimentService
{
    public function sync(Collection $collection, array $attributes, ?User $actor = null): Collection
    {
        $payload = [
            'experiment_key' => array_key_exists('experiment_key', $attributes) ? ($attributes['experiment_key'] ?: null) : $collection->experiment_key,
            'experiment_treatment' => array_key_exists('experiment_treatment', $attributes) ? ($attributes['experiment_treatment'] ?: null) : $collection->experiment_treatment,
            'placement_variant' => array_key_exists('placement_variant', $attributes) ? ($attributes['placement_variant'] ?: null) : $collection->placement_variant,
            'ranking_mode_variant' => array_key_exists('ranking_mode_variant', $attributes) ? ($attributes['ranking_mode_variant'] ?: null) : $collection->ranking_mode_variant,
            'collection_pool_version' => array_key_exists('collection_pool_version', $attributes) ? ($attributes['collection_pool_version'] ?: null) : $collection->collection_pool_version,
            'test_label' => array_key_exists('test_label', $attributes) ? ($attributes['test_label'] ?: null) : $collection->test_label,
        ];

        $before = [
            'experiment_key' => $collection->experiment_key,
            'experiment_treatment' => $collection->experiment_treatment,
            'placement_variant' => $collection->placement_variant,
            'ranking_mode_variant' => $collection->ranking_mode_variant,
            'collection_pool_version' => $collection->collection_pool_version,
            'test_label' => $collection->test_label,
        ];

        $collection->forceFill($payload)->save();
        $fresh = $collection->fresh();

        app(CollectionHistoryService::class)->record(
            $fresh,
            $actor,
            'experiment_metadata_updated',
            'Collection experiment metadata updated.',
            $before,
            $payload,
        );

        return $fresh;
    }
}