<?php

namespace apexl\Io\modules\user\controllers;

use apexl\Io\includes\Controller;
use apexl\Io\modules\user\entities\roleEntity;
use apexl\Io\modules\user\services\Permissions;
use apexl\Io\services\HttpPaths;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final readonly class rolesController extends Controller
{
    /**
     * @method POST
     * @throws \Exception
     * Automatic install method. Runs the core IO installation process, requires Database user and pass as a minimum to run.
     */
    public function createUpdate(
        HttpPaths $path,
        Permissions $permissions,
        ServerRequestInterface $request,
        ResponseInterface $response,
        $args
    ): ResponseInterface {
        $body = (object) $request->getParsedBody();

        $role = new roleEntity();
        //check if this is an update or create.
        if ($id = $args["id"] ?? false) {
            $role->load($id);
            if ($role->id === null) {
                $this->output->addResponse($request, [], false); //added so we can hook into this elsewhere.
                return $this->throw404($response);
            }
        }

        $role->name = $body->name;
        $role->permissions = serialize([]);
        unset($body->name);

        $role->store();

        foreach ($permissions as $macName => $data) {
            $permission = constant($macName);
            if ($body->$macName == 'true') {
                $role->addPermission($permission);
            } elseif ($body->$macName == 'false') {
                $role->removePermission($permission);
            }
        }

        $role->store();
        $this->output->addMessage(
            $path->getRouteName($request) . '.validation',
            'success',
            $role->name . ' ' . ($id ? 'updated' : 'created')
        );
        $this->output->addResponse($request); //added so we can hook into this elsewhere.
        return $this->json($response);
    }

    // Removed: getRoles() (roleEntity.get). It called $this->getEntityData(),
    // which does not exist on Controller — the method could never run. Role
    // listing lives in apexl/io-permissions.
}
