<?php

declare(strict_types=1);

namespace PortalPeople\reports\controllers\api;

use OpenApi\Annotations as OA;
use PortalPeople\reports\Module as ReportsModule;
use Yii;
use yii\rest\Controller;
use yii\web\Response;

/**
 * @OA\Tag(
 *   name="Reports",
 *   description="Report generation endpoints — bestsellers, turnover-by-day, and generic named reports"
 * )
 */
class ReportsController extends Controller
{
    /**
     * @OA\Post(
     *   path="/v1/reports/validate",
     *   tags={"Reports"},
     *   summary="AJAX validation for report form",
     *   @OA\Response(response=200, description="Validation result JSON")
     * )
     *
     * @return array<string, mixed>
     */
    public function actionValidate(): array
    {
        /** @var ReportsModule $module */
        $module = Yii::$app->getModule('ngauge-reports');

        return $module->getReportsService()->validate();
    }

    /**
     * @OA\Post(
     *   path="/v1/reports/report",
     *   tags={"Reports"},
     *   summary="Run a named report",
     *   @OA\Response(response=200, description="Report data"),
     *   @OA\Response(response=400, description="Validation errors")
     * )
     *
     * @return array<string, mixed>
     */
    public function actionReport(): array
    {
        /** @var ReportsModule $module */
        $module = Yii::$app->getModule('ngauge-reports');

        return $module->getReportsService()->runReport();
    }

    /**
     * @OA\Post(
     *   path="/v1/reports/bestsellers",
     *   tags={"Reports"},
     *   summary="Render bestsellers report",
     *   @OA\Response(response=200, description="Rendered HTML or validation errors")
     * )
     */
    public function actionBestsellers(): Response|array
    {
        /** @var ReportsModule $module */
        $module = Yii::$app->getModule('ngauge-reports');
        $data = $module->getReportsService()->bestsellers();

        if ($data['result'] === null && Yii::$app->request->isAjax) {
            return $data['model']->errors;
        }

        return $this->render('@backend/views/reports/_bestsellers', $data);
    }

    /**
     * @OA\Post(
     *   path="/v1/reports/turnoverbyday",
     *   tags={"Reports"},
     *   summary="Render turnover-by-day report",
     *   @OA\Response(response=200, description="Rendered HTML or validation errors")
     * )
     */
    public function actionTurnoverbyday(): Response|array
    {
        /** @var ReportsModule $module */
        $module = Yii::$app->getModule('ngauge-reports');
        $data = $module->getReportsService()->turnoverbyday();

        if ($data['result'] === null && Yii::$app->request->isAjax) {
            return $data['model']->errors;
        }

        return $this->render('@backend/views/reports/_turnoverbyday', $data);
    }
}
