<?php

namespace App\Http\Controllers\Misc;

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

class AvatarController
{
    protected $service;

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

    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($user->id, $file);
            return response()->json([
                'success' => true,
                'hash' => $hash,
                'url' => AvatarUrl::forUser((int) $user->id, $hash, 128),
            ], 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);
        }
    }
}
