<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Appends;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;

#[Appends(['created_at_formatted', 'type_label'])]
class StockMutation extends Model
{
    protected $guarded = ['id'];

    protected function casts(): array
    {
        return [
            'quantity' => 'decimal:4',
            'stock_before' => 'decimal:4',
            'stock_after' => 'decimal:4',
        ];
    }

    public function createdAtFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->created_at?->translatedFormat('l, d F Y H:i'),
        );
    }

    public function typeLabel(): Attribute
    {
        return Attribute::make(
            get: fn () => match ($this->type) {
                'in' => 'Masuk',
                'out' => 'Keluar',
                'transfer' => 'Transfer',
                'adjustment' => 'Penyesuaian',
                default => $this->type,
            },
        );
    }

    public function stockable(): MorphTo
    {
        return $this->morphTo();
    }

    public function source(): MorphTo
    {
        return $this->morphTo();
    }

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