<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

/**
 * PRC-817 — Rack/kabin. total_u = kapasite (U); row string alan (ayrı model değil).
 */
class Rack extends Model
{
    use HasFactory;

    protected $fillable = [
        'datacenter_id',
        'name',
        'row',
        'total_u',
        'notes',
    ];

    protected $casts = [
        'total_u' => 'integer',
    ];

    public function datacenter(): BelongsTo
    {
        return $this->belongsTo(Datacenter::class);
    }

    public function servers(): HasMany
    {
        return $this->hasMany(Server::class);
    }

    /**
     * Bu kabinde kullanılan U sayısı (yerleştirilmiş sunucuların u_size toplamı).
     */
    public function usedU(): int
    {
        return (int) $this->servers()->sum('u_size');
    }

    public function freeU(): int
    {
        return max(0, (int) $this->total_u - $this->usedU());
    }
}
