<?php
declare(strict_types=1);

namespace App\Controllers\Api;

use App\Middleware\ApiToken;
use App\Middleware\TenantScope;
use App\Models\Asset;
use App\Models\AssetType;
use App\Models\AssetTypeField;
use Core\Controller;

final class AssetsController extends Controller
{
    public function middleware(): array
    {
        return [ApiToken::class, TenantScope::class];
    }

    private function tenantId(): int
    {
        return (int) ($_SESSION['tenant_id'] ?? 0);
    }

    public function index(): void
    {
        $tenantId = $this->tenantId();
        $filters  = [
            'site_id'       => $_GET['site_id']       ?? null,
            'asset_type_id' => $_GET['asset_type_id'] ?? null,
            'status'        => $_GET['status']        ?? null,
            'q'             => $_GET['q']             ?? null,
        ];
        $this->json([
            'data' => Asset::listForTenant($tenantId, array_filter($filters)),
        ]);
    }

    public function show(int $id): void
    {
        $tenantId = $this->tenantId();
        $asset = Asset::findInTenant($tenantId, $id);
        if (!$asset) $this->json(['error' => 'Not found'], 404);
        $asset['meta'] = !empty($asset['meta_json']) ? json_decode($asset['meta_json'], true) : new \stdClass();
        $asset['schema'] = AssetTypeField::forType($tenantId, (int) $asset['asset_type_id']);
        $this->json(['data' => $asset]);
    }

    public function types(): void
    {
        $tenantId = $this->tenantId();
        $types = AssetType::optionsForTenant($tenantId);
        foreach ($types as &$t) {
            $t['fields'] = AssetTypeField::forType($tenantId, (int) $t['asset_type_id']);
        }
        $this->json(['data' => $types]);
    }
}
