<?php

declare(strict_types=1);

namespace OCA\GlxRadio\Controller;

use OCP\AppFramework\Controller;
use OCP\AppFramework\Http\Attribute\NoAdminRequired;
use OCP\AppFramework\Http\JSONResponse;
use OCP\IConfig;
use OCP\IRequest;
use OCP\IUserSession;

class FavoritesController extends Controller {
    public function __construct(
        string $appName,
        IRequest $request,
        private IConfig $config,
        private IUserSession $userSession,
    ) {
        parent::__construct($appName, $request);
    }

    private function getUserId(): ?string {
        $user = $this->userSession->getUser();
        return $user ? $user->getUID() : null;
    }

    /**
     * Liefert die gespeicherte Favoritenliste des angemeldeten Nutzers.
     */
    #[NoAdminRequired]
    public function list(): JSONResponse {
        $uid = $this->getUserId();
        if (!$uid) {
            return new JSONResponse(['favorites' => []]);
        }
        $raw = $this->config->getUserValue($uid, 'glxradio', 'favorites', '[]');
        $favorites = json_decode($raw, true);
        if (!is_array($favorites)) {
            $favorites = [];
        }
        return new JSONResponse(['favorites' => $favorites]);
    }

    /**
     * Speichert die komplette Favoritenliste des angemeldeten Nutzers
     * (das Frontend schickt jeweils die volle, aktualisierte Liste).
     */
    #[NoAdminRequired]
    public function save(array $favorites = []): JSONResponse {
        $uid = $this->getUserId();
        if (!$uid) {
            return new JSONResponse(['error' => 'Nicht angemeldet.'], 401);
        }
        $this->config->setUserValue($uid, 'glxradio', 'favorites', json_encode($favorites));
        return new JSONResponse(['status' => 'ok']);
    }
}
