<?php

namespace Modules\Auth\Services;

use App\Models\User;
use Illuminate\Support\Facades\DB;
use Modules\Auth\Transformers\AuthUserResource;
use Modules\Core\Services\ImageUpload;

class ProfileService
{
    public function __construct(
        protected ImageUpload $imageUpload,
    ) {}

    public function profile(User $user)
    {
        return (new AuthUserResource($user))->additional([
            'status'  => true,
            'message' => 'Profile return successfully.',
        ]);
    }

    public function update(User $user, array $data): ?User
    {
        return DB::transaction(function () use ($user, $data) {

            $updateData = [
                'name'  => $data['name'] ?? $user->name,
                'email' => $data['email'] ?? $user->email,
                'phone' => $data['phone'] ?? $user->phone,
            ];

            if (!empty($data['image'])) {
                $this->imageUpload->fileUpload(
                    file: $data['image'],
                    data: $user,
                    folder: 'auth/profile',
                    width: 300,
                    height: 300,
                );
            }
            
            if (!empty($data['sign'])) {
                $this->imageUpload->fileUpload(
                    file: $data['sign'],
                    data: $user,
                    folder: 'auth/signature',
                    width: 300,
                    height: 80,
                    property: 'sign',
                );
            }

            $user->update($updateData);

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