<?php

namespace App\Models;

use App\Models\Concerns\InteractsWithActivityLog;
use Illuminate\Database\Eloquent\Attributes\Appends;
use Illuminate\Database\Eloquent\Attributes\Guarded;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

#[Guarded(['id'])]
#[Appends([
    'material_usage_formatted',
    'material_usage_input',
    'unit_abbreviation',
])]
class CuttingMaterial extends Model
{
    // 1. Use Trait
    use HasFactory, InteractsWithActivityLog, SoftDeletes;

    // 2. Casting
    protected function casts(): array
    {
        return [
            'material_usage' => 'decimal:4',
        ];
    }

    // 3. Attribute
    public function materialUsageFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->formatQuantity($this->material_usage),
        );
    }

    public function materialUsageInput(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->formatQuantityInput($this->material_usage),
        );
    }

    public function unitAbbreviation(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->attributes['unit_abbreviation']
                ?? $this->rawMaterialPrice?->rawMaterial?->unit?->abbreviation(),
        );
    }

    // 4. Other Methods
    public function materialCost(): int
    {
        $price = $this->rawMaterialPrice;

        if ($price === null) {
            return 0;
        }

        return (int) round((float) $this->material_usage * (int) $price->price);
    }

    private function formatQuantity(float|string|null $value): string
    {
        $formatted = rtrim(rtrim(number_format((float) $value, 4, ',', '.'), '0'), ',');

        return "{$formatted} {$this->unitAbbreviation}";
    }

    private function formatQuantityInput(float|string|null $value): string
    {
        return rtrim(rtrim(number_format((float) $value, 4, '.', ''), '0'), '.');
    }

    // 5. Relation
    public function cutting(): BelongsTo
    {
        return $this->belongsTo(Cutting::class);
    }

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

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