<?php

namespace App\Master\Http\Resources;

use App\Master\Models\ApiToken;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\Tenant;

class ApiUserView extends JsonResource
{
    public static $wrap = '';

    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $this->resource->load('tokens');
        $this->resource->token_types = [
            [
                'name' => 'OAuth flow to get access token',
                'value' => ApiToken::TYPE_OAUTH,
            ],
            [
                'name' => 'Simple persistent API Token',
                'value' => ApiToken::TYPE_PERSISTENT,
            ],
        ];

        $this->resource->tenants = $this->resource->tenants->pluck('tenant_id');
        $this->resource['tenant_list'] = Tenant::all()->map(fn(Tenant $tenant) => [
            'name' => $tenant->name,
            'value' => $tenant->id,
        ]);
        if (!empty($this->resource->client_secret)) {
            $this->resource->client_secret = decrypt($this->resource->client_secret);
        }


        $usage_data = $this->resource->apiUsage()
            ->where('time_window', '>=', Carbon::now()->subMonth())
            ->get()
            ->groupBy('time_window')
            ->map(fn($group) => $group->sum('hits'));

        $this->resource->usage_data = [
            'labels' => $usage_data->keys(),
            'datasets' => [
                [
                    'label' => 'API Hits',
                    'backgroundColor' => '#600000',
                    'data' => $usage_data,
                    'tension' => 0.5
                ],
            ],
        ];
        return parent::toArray($request);
    }
}
