<?php
declare(strict_types=1);

namespace App\Models;

use Core\DB;
use Core\Model;

final class AssetType extends Model
{
    protected string $table = 'asset_types';
    protected string $primaryKey = 'asset_type_id';

    public static function listForTenant(int $tenantId): array
    {
        return DB::all(
            'SELECT t.*,
                    (SELECT COUNT(*) FROM assets a WHERE a.asset_type_id = t.asset_type_id AND a.deleted_at IS NULL) AS asset_count,
                    (SELECT COUNT(*) FROM asset_type_fields f WHERE f.asset_type_id = t.asset_type_id) AS field_count
               FROM asset_types t
              WHERE t.tenant_id = :t AND t.deleted_at IS NULL
              ORDER BY t.sort_order, t.name',
            ['t' => $tenantId]
        );
    }

    public static function optionsForTenant(int $tenantId): array
    {
        return DB::all(
            'SELECT asset_type_id, code, name, icon, color
               FROM asset_types
              WHERE tenant_id = :t AND deleted_at IS NULL AND status = "active"
              ORDER BY sort_order, name',
            ['t' => $tenantId]
        );
    }

    public static function findInTenant(int $tenantId, int $typeId): ?array
    {
        return DB::one(
            'SELECT * FROM asset_types WHERE tenant_id = :t AND asset_type_id = :id AND deleted_at IS NULL',
            ['t' => $tenantId, 'id' => $typeId]
        );
    }

    public static function create(int $tenantId, int $userId, array $data): int
    {
        return (int) DB::insert('asset_types', [
            'tenant_id'   => $tenantId,
            'code'        => $data['code'],
            'name'        => $data['name'],
            'description' => $data['description'] ?? null,
            'icon'        => $data['icon']        ?? null,
            'color'       => $data['color']       ?? null,
            'sort_order'  => (int) ($data['sort_order'] ?? 0),
            'status'      => $data['status']      ?? 'active',
            'created_by'  => $userId,
        ]);
    }

    public static function update(int $tenantId, int $typeId, array $data): void
    {
        $allowed = ['code','name','description','icon','color','sort_order','status'];
        $set = [];
        $params = ['t' => $tenantId, 'id' => $typeId];
        foreach ($allowed as $col) {
            if (array_key_exists($col, $data)) {
                $set[] = "`{$col}` = :{$col}";
                $params[$col] = $col === 'sort_order' ? (int) $data[$col] : $data[$col];
            }
        }
        if (!$set) return;
        DB::run(
            'UPDATE asset_types SET ' . implode(', ', $set) . ' WHERE tenant_id = :t AND asset_type_id = :id',
            $params
        );
    }

    public static function softDelete(int $tenantId, int $typeId): void
    {
        DB::run(
            'UPDATE asset_types SET deleted_at = NOW() WHERE tenant_id = :t AND asset_type_id = :id',
            ['t' => $tenantId, 'id' => $typeId]
        );
    }
}
