<?php

declare(strict_types=1);

namespace backend\modules\api\controllers;

use common\services\DietPlanService;
use yii\filters\VerbFilter;
use yii\web\Controller;
use yii\web\Response;

/**
 * API DietController — food suggestions for diet builder autocomplete.
 */
class DietController extends Controller
{
    public $enableCsrfValidation = false;

    public function behaviors(): array
    {
        return [
            'verbs' => [
                'class'   => VerbFilter::class,
                'actions' => ['suggest' => ['GET']],
            ],
        ];
    }

    /**
     * GET /api/food-suggest?q=chicken
     */
    public function actionSuggest(): array
    {
        \Yii::$app->response->format = Response::FORMAT_JSON;

        $query   = (string)\Yii::$app->request->get('q', '');
        $userId  = \Yii::$app->user->isGuest ? null : (int)\Yii::$app->user->id;
        $service = new DietPlanService();

        $foods = $service->getFoodSuggestions($query, $userId, 15);

        return array_map(fn($f) => [
            'id'       => $f['id'],
            'name'     => $f['name'],
            'category' => $f['category'],
            'calories' => $f['calories'],
            'protein'  => $f['protein'],
            'carbs'    => $f['carbs'],
            'fats'     => $f['fats'],
        ], $foods);
    }
}
