<?php

namespace App\Actions\Profile;

use App\Models\PlayerProfile;
use App\Services\ProfileCompletionService;
use Illuminate\Support\Facades\DB;

class UpdatePlayerProfileAction
{
    public function __construct(
        private ProfileCompletionService $completionService,
    ) {}

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

            if (array_key_exists('username', $data)) {
                $user->username = $data['username'];
            }

            if (array_key_exists('display_name', $data)) {
                $user->display_name = $data['display_name'];
                $profile->display_name = $data['display_name'];
            }

            $user->save();

            $profile->fill([
                'bio' => $data['bio'] ?? $profile->bio,
                'country_code' => $data['country_code'] ?? $profile->country_code,
                'city' => $data['city'] ?? $profile->city,
                'timezone' => $data['timezone'] ?? $profile->timezone,
                'birth_date' => $data['birth_date'] ?? $profile->birth_date,
                'looking_for_team' => $data['looking_for_team'] ?? $profile->looking_for_team,
                'profile_visibility' => $data['profile_visibility'] ?? $profile->profile_visibility,
            ]);

            $profile->profile_completion_percentage = $this->completionService->calculate($profile);
            $profile->save();

            return $profile->fresh();
        });
    }
}
