<?php

declare(strict_types=1);

namespace PortalPeople\documentdesigner\controllers\api;

use OpenApi\Annotations as OA;
use PortalPeople\documentdesigner\Module as DocumentDesignerModule;
use Yii;
use yii\rest\Controller;
use yii\web\Response;

/**
 * @OA\Tag(
 *   name="OCR",
 *   description="Optical character recognition file scanning"
 * )
 */
class OcrController extends Controller
{
    /**
     * @OA\Post(
     *   path="/v1/ocr/rename",
     *   tags={"OCR"},
     *   summary="Scan an uploaded file using OCR",
     *   @OA\RequestBody(
     *     required=true,
     *     @OA\MediaType(
     *       mediaType="multipart/form-data",
     *       @OA\Schema(@OA\Property(property="OcrFile", type="string", format="binary"))
     *     )
     *   ),
     *   @OA\Response(response=200, description="OCR scan result"),
     *   @OA\Response(response=503, description="Module unavailable")
     * )
     */
    public function actionRename(): Response|array
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        /** @var DocumentDesignerModule|null $module */
        $module = Yii::$app->getModule('documentdesigner');

        if (!$module instanceof DocumentDesignerModule) {
            Yii::$app->response->statusCode = 503;
            return ['error' => 'Document designer module unavailable'];
        }

        return $module->getOcrService()->scanFile($_FILES['OcrFile'] ?? []);
    }
}
