<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Http\Requests\AvatarUploadRequest;
use App\Services\AvatarService;
use App\Support\AvatarUrl;
use Illuminate\Http\JsonResponse;
use RuntimeException;

class AvatarController extends Controller
{
    protected $service;

    public function __construct(AvatarService $service)
    {
        $this->service = $service;
    }

    /**
     * Handle avatar upload request.
     */
    public function upload(AvatarUploadRequest $request): JsonResponse
    {
        $user = $request->user();
        if (!$user) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        $file = $request->file('avatar');

        try {
            $hash = $this->service->storeFromUploadedFile(
                (int) $user->id,
                $file,
                (string) $request->input('avatar_position', 'center')
            );
            return response()->json([
                'success' => true,
                'hash' => $hash,
                'url' => AvatarUrl::forUser((int) $user->id, $hash, 256),
            ], 200);
        } catch (RuntimeException $e) {
            logger()->warning('Avatar upload validation failed', [
                'user_id' => (int) $user->id,
                'message' => $e->getMessage(),
            ]);

            return response()->json([
                'error' => 'Validation failed',
                'message' => $e->getMessage(),
            ], 422);
        } catch (\Throwable $e) {
            logger()->error('Avatar upload failed', [
                'user_id' => (int) $user->id,
                'message' => $e->getMessage(),
            ]);

            return response()->json(['error' => 'Processing failed'], 500);
        }
    }
}
