<?php

namespace App\Actions\Records;

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

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

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

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

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

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

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