<?php

/**
 * @uri /audit-log
 */
class AuditLogListController extends \CfProtectedResource
{
    /**
     * @rbacName View audit log
     * @rbacGroup Audit log
     * @rbacAlias audit-log.view
     */
    public function get($request): \Response
    {
        $auditLogModel = new AuditLogModel();
        $response = new \Response($request);
        $args = AuditLogListArgumentsValidator::validate($_GET);

        $arguments = AuditLogListArgumentsDto::fromArray($args);
        $logs = $auditLogModel->list($arguments);
        $response->code = \Response::OK;
        $response->body = json_encode($logs);

        return $response;
    }
}

/**
 * @uri /audit-log/:id
 */
class AuditLogController extends \CfProtectedResource
{
    /**
     * @rbacAlias audit-log.view
     */
    public function get($request, $id): \Response
    {
        $auditLogModel = new AuditLogModel();
        $response = new \Response($request);

        if (empty($id)) {
            throw new \InvalidArgumentException("ID cannot be empty.");
        }

        $log = $auditLogModel->item((int) $id);
        if (!$log) {
            throw new ResponseException("Not found.", Response::NOTFOUND);
        }

        $response->code = \Response::OK;
        $response->body = json_encode($log);

        return $response;
    }
}

/**
 * @uri /audit-log/:type/names
 */
class AuditLogNamesByTypeController extends \CfProtectedResource
{
    /**
     * @rbacAlias audit-log.view
     */
    public function get($request, $type): \Response
    {
        $auditLogModel = new AuditLogModel();
        $response = new \Response($request);
        $type = rawurldecode($type);

        if (empty($type)) {
            throw new \InvalidArgumentException("Type cannot be empty.");
        }

        if (!in_array($type, AuditLogObjectTypes::ALLOWED_TYPES)) {
            throw new \InvalidArgumentException("Object type is not allowed.");
        }

        $names = $auditLogModel->namesByType($type);
        $response->code = \Response::OK;
        $response->body = json_encode($names);

        return $response;
    }
}

/**
 * @uri /audit-log/actors
 */
class AuditLogActorsController extends \CfProtectedResource
{
    /**
     * @rbacAlias audit-log.view
     */
    public function get($request): \Response
    {
        $auditLogModel = new AuditLogModel();
        $response = new \Response($request);

        $names = $auditLogModel->actors();
        $response->code = \Response::OK;
        $response->body = json_encode($names);

        return $response;
    }
}
