<?php

namespace App\Actions\Events;

use App\Enums\EventStatus;
use App\Models\Event;
use App\Models\User;
use App\Services\AuditLogger;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;

class PublishEventAction
{
    public function __construct(private AuditLogger $auditLogger) {}

    public function execute(Event $event, User $admin): Event
    {
        return DB::transaction(function () use ($event, $admin) {
            if ($event->status === EventStatus::Cancelled) {
                throw new InvalidArgumentException(__('events.errors.invalid_status'));
            }

            $old = $event->only(['status', 'published_at']);

            $event->update([
                'status' => EventStatus::RegistrationOpen,
                'published_at' => $event->published_at ?? now(),
            ]);

            $this->auditLogger->log('event.published', $event, $old, $event->only(['status', 'published_at']));

            return $event->fresh(['game']);
        });
    }
}
