<?php
declare(strict_types=1);

namespace App\Modules\TrainerPortal\Controllers\Api;

use App\Core\ApiController;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Core\ApiErrorCodes;
use App\Shared\Services\PhotoUploadService;

final class PhotoController extends ApiController
{
    public function upload(Request $request): Response
    {
        $coach = App::getInstance()->currentCoach();
        $file = $_FILES['photo'] ?? null;

        if (!$file || !PhotoUploadService::isUploaded($file)) {
            return $this->errorResponse('يرجى إرفاق صورة', 422, [], ApiErrorCodes::VALIDATION_FAILED);
        }

        $validation = PhotoUploadService::validate($file);
        if (!$validation['valid']) {
            return $this->errorResponse($validation['error'] ?? 'صورة غير صالحة', 422, [], ApiErrorCodes::VALIDATION_FAILED);
        }

        $result = PhotoUploadService::upload($file, 'coaches', (int) $coach->id);
        if (!$result) {
            return $this->errorResponse('فشل رفع الصورة', 500, [], ApiErrorCodes::SERVER_ERROR);
        }

        $db = App::getInstance()->db();
        $db->update('coaches', [
            'photo_path' => $result['path'],
        ], 'id = ?', [(int) $coach->id]);

        return $this->successResponse([
            'photo_path' => $result['path'],
            'thumbnail_path' => $result['thumbnail_path'] ?? null,
        ]);
    }
}
