<?php

namespace App\Actions\Videos;

use App\Enums\ProfileVisibility;
use App\Enums\VideoType;
use App\Models\Game;
use App\Models\PlayerGameProfile;
use App\Models\PlayerVideo;
use App\Models\User;
use App\Services\ContentModerationService;
use App\Services\VideoUrlParserService;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;

class CreatePlayerVideoAction
{
    public function __construct(
        private VideoUrlParserService $urlParser,
        private ContentModerationService $moderation,
    ) {}

    public function execute(User $user, array $data): PlayerVideo
    {
        return DB::transaction(function () use ($user, $data) {
            $profile = $user->playerProfile;

            if ($profile === null) {
                throw new InvalidArgumentException(__('events.registration.profile_incomplete'));
            }

            $parsed = $this->urlParser->parse($data['original_url']);

            $gameProfileId = $data['player_game_profile_id'] ?? null;
            $gameId = $data['game_id'] ?? null;

            if ($gameProfileId) {
                $gameProfile = PlayerGameProfile::query()
                    ->where('player_profile_id', $profile->id)
                    ->whereKey($gameProfileId)
                    ->firstOrFail();

                $gameId = $gameProfile->game_id;
            }

            if ($gameId) {
                Game::query()->findOrFail($gameId);
            }

            $moderationStatus = $this->moderation->initialStatus();

            return PlayerVideo::query()->create([
                'player_profile_id' => $profile->id,
                'player_game_profile_id' => $gameProfileId,
                'game_id' => $gameId,
                'title' => $data['title'],
                'description' => $data['description'] ?? null,
                'original_url' => $data['original_url'],
                'provider' => $parsed['provider'],
                'external_video_id' => $parsed['external_video_id'],
                'normalized_url' => $parsed['normalized_url'],
                'safe_embed_url' => $parsed['safe_embed_url'],
                'thumbnail_url' => $parsed['thumbnail_url'],
                'video_type' => VideoType::from($data['video_type']),
                'visibility' => ProfileVisibility::from($data['visibility'] ?? ProfileVisibility::Public->value),
                'moderation_status' => $moderationStatus,
                'published_at' => $moderationStatus->value === 'approved' ? now() : null,
            ]);
        });
    }
}
