<?php

namespace App\Actions\Profile;

use App\Models\PlayerProfile;
use App\Services\MediaUploadService;
use App\Services\ProfileCompletionService;
use Illuminate\Http\UploadedFile;
use InvalidArgumentException;

class UploadProfileImageAction
{
    public function __construct(
        private MediaUploadService $mediaUpload,
        private ProfileCompletionService $completionService,
    ) {}

    public function execute(PlayerProfile $profile, UploadedFile $file, string $type): PlayerProfile
    {
        if (! in_array($type, ['avatar', 'cover'], true)) {
            throw new InvalidArgumentException(__('validation.image_type_invalid'));
        }

        $rules = config("esports.uploads.{$type}", []);
        $disk = 'profiles';
        $directory = "users/{$profile->user_id}/{$type}";
        $field = $type === 'avatar' ? 'avatar_path' : 'cover_path';

        $this->mediaUpload->deleteIfExists($disk, $profile->{$field});

        $upload = $this->mediaUpload->uploadImage($file, $disk, $directory, $rules);

        $profile->{$field} = $upload['path'];
        $profile->profile_completion_percentage = $this->completionService->calculate($profile);
        $profile->save();

        return $profile->fresh();
    }
}
