<?php

namespace App\Actions\Videos;

use App\Enums\ModerationStatus;
use App\Events\ContentModerated;
use App\Models\PlayerVideo;
use App\Models\User;
use App\Services\AuditLogger;
use Illuminate\Support\Facades\DB;

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

    public function execute(
        PlayerVideo $video,
        ModerationStatus $status,
        User $admin,
        ?string $reason = null,
    ): PlayerVideo {
        return DB::transaction(function () use ($video, $status, $admin, $reason) {
            $old = $video->only(['moderation_status', 'moderation_reason', 'published_at']);
            $previousStatus = $video->moderation_status;

            $video->update([
                'moderation_status' => $status,
                'moderation_reason' => $reason,
                'published_at' => $status === ModerationStatus::Approved ? ($video->published_at ?? now()) : null,
            ]);

            $this->auditLogger->log(
                'video.moderated',
                $video,
                $old,
                $video->only(['moderation_status', 'moderation_reason', 'published_at']),
            );

            event(new ContentModerated(
                content: $video->fresh(['playerProfile.user']),
                previousStatus: $previousStatus,
                newStatus: $status,
                reason: $reason,
            ));

            return $video->fresh(['game', 'playerProfile.user']);
        });
    }
}
