<?php

namespace routes;

use classes\bird;
use traits\bird_route_helpers_t;
use traits\route_t;

class birdNumbersRoute
{
    use route_t, bird_route_helpers_t;

    public function run(): void
    {
        // List owned numbers
        $this->get('/bird/numbers', function () {
            global $response;
            // Permission: list numbers via Bird
            self::requirePermission('modules_bird_numbers_list');
            $client = new bird();
            $ws = $this->normalizeOptionalString($this->fromQuery('workspaceId'));
            if ($ws === '') {
                $ws = $this->getConfiguredWorkspaceId($client);
            }
            if ($ws === '') {
                $response->error('Missing required parameter: workspaceId', 400);
            }
            $query = $this->getParametersAsArray();
            unset($query['workspaceId']);
            $res = $client->listNumbers($ws, $query);
            $response->success($res ?? []);
        }, [
            'modules_bird_numbers_list' => 'List your numbers via Bird',
        ]);

        // Get a specific number by ID
        $this->get('/bird/numbers/{id}', function () {
            global $response;
            self::requirePermission('modules_bird_numbers_get');
            $id = (string)$this->fromRoute('id');
            if ($id === '') {
                $response->error('Missing id', 400);
            }
            $client = new bird();
            $ws = $this->normalizeOptionalString($this->fromQuery('workspaceId'));
            if ($ws === '') {
                $ws = $this->getConfiguredWorkspaceId($client);
            }
            if ($ws === '') {
                $response->error('Missing required parameter: workspaceId', 400);
            }
            $res = $client->getNumber($ws, $id);
            $response->success($res ?? []);
        }, [
            'modules_bird_numbers_get' => 'Get a number by ID via Bird',
        ]);

        // Release/delete a number by ID (if supported in your Bird account)
        $this->delete('/bird/numbers/{id}', function () {
            global $response;
            self::requirePermission('modules_bird_numbers_delete');
            $id = (string)$this->fromRoute('id');
            if ($id === '') {
                $response->error('Missing id', 400);
            }
            $client = new bird();
            $ws = $this->normalizeOptionalString($this->fromRequest('workspaceId') ?? $this->fromQuery('workspaceId'));
            if ($ws === '') {
                $ws = $this->getConfiguredWorkspaceId($client);
            }
            if ($ws === '') {
                $response->error('Missing required parameter: workspaceId', 400);
            }
            $res = $client->deleteNumber($ws, $id);
            $response->success($res ?? ['status' => 'ok']);
        }, [
            'modules_bird_numbers_delete' => 'Delete/release a number via Bird',
        ]);
    }
}
