<?php

namespace App\Models;

use App\Enums\RawMaterialUnit;
use Illuminate\Database\Eloquent\Attributes\Appends;
use Illuminate\Database\Eloquent\Attributes\Guarded;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

#[Appends(['formatted_name', 'unit_label'])]
#[Guarded(['id'])]
class RawMaterial extends Model
{
    use HasFactory, SoftDeletes;

    protected function casts(): array
    {
        return [
            'unit' => RawMaterialUnit::class,
            'is_active' => 'boolean',
        ];
    }

    protected function formattedName(): Attribute
    {
        return Attribute::make(
            get: fn () => ucfirst($this->name),
        );
    }

    protected function unitLabel(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->unit->label(),
        );
    }

    #[Scope]
    protected function active(Builder $query): void
    {
        $query->where('is_active', true);
    }

    #[Scope]
    protected function nonactive(Builder $query): void
    {
        $query->where('is_active', false);
    }

    #[Scope]
    protected function kg(Builder $query): void
    {
        $query->where('unit', RawMaterialUnit::KG);
    }

    #[Scope]
    protected function meter(Builder $query): void
    {
        $query->where('unit', RawMaterialUnit::METER);
    }

    #[Scope]
    protected function yard(Builder $query): void
    {
        $query->where('unit', RawMaterialUnit::YARD);
    }

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