<?php

namespace routes;

use classes\module_usage_service;
use Exception;
use traits\route_t;

class moduleUsageRoute
{
    use route_t;

    public function run(): void
    {
        $this->get('/modules/usage/summary', function () {
            global $response;

            $this->requirePermission('modules_usage_view');
            $response->success((new module_usage_service())->summary([
                'module' => $this->getParameter('module'),
                'period' => $this->getParameter('period'),
                'status' => $this->getParameter('status'),
                'date' => $this->getParameter('date'),
            ]));
        }, [
            'modules_usage_view' => 'View module usage, quota, and statistics summaries',
        ]);

        $this->get('/modules/usage/{moduleKey}', function () {
            global $response;

            $this->requirePermission('modules_usage_view');
            $moduleKey = (string)($this->fromRoute('moduleKey') ?? '');
            $response->success((new module_usage_service())->moduleDetail($moduleKey, [
                'period' => $this->getParameter('period'),
                'date' => $this->getParameter('date'),
                'limit' => $this->getParameter('limit'),
            ]));
        }, [
            'modules_usage_view' => 'View detailed module usage, quota, and statistics history',
        ]);

        $this->patch('/modules/quotas/{moduleKey}/{metricKey}', function () {
            global $response;

            $this->requirePermission('modules_quotas_manage');
            $moduleKey = (string)($this->fromRoute('moduleKey') ?? '');
            $metricKey = (string)($this->fromRoute('metricKey') ?? '');

            try {
                $response->success((new module_usage_service())->updateQuotaSetting(
                    $moduleKey,
                    $metricKey,
                    $response->getAllRequestParameters()
                ));
            } catch (Exception $exception) {
                if ($exception->getMessage() === 'quota_not_writable') {
                    $response->error([
                        'message' => 'Quota limit is not writable for this provider or derived metric.',
                        'code' => 'quota_not_writable',
                    ], 409);
                }

                $response->error($exception->getMessage(), 422);
            }
        }, [
            'modules_quotas_manage' => 'Manage module quota enforcement and writable hard limits',
        ]);
    }
}
