<?php

namespace App\Models;

use App\Enums\OwnerVerificationStatus;
use App\Enums\RawMaterialUnit;
use App\Models\Concerns\HasPendingOwnerVerification;
use App\Models\Concerns\InteractsWithActivityLog;
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\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Database\Eloquent\SoftDeletes;

#[Guarded(['id'])]
#[Appends(['unit_abbreviation', 'unit_label', 'total_stock_formatted', 'total_inventory_value_formatted'])]
class RawMaterial extends Model
{
    // 1. Use Trait
    use HasFactory, HasPendingOwnerVerification, InteractsWithActivityLog, SoftDeletes;

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

    // 3. Scope (grouped by column, then alphabetical)
    // Column Group: is_active
    #[Scope]
    protected function active(Builder $query): void
    {
        $query->where('is_active', true);
    }

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

    // 4. Attribute
    public function unitAbbreviation(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->unit->abbreviation(),
        );
    }

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

    public function totalInventoryValueFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => 'Rp '.number_format(
                $this->prices->sum(fn (RawMaterialPrice $price) => (float) $price->stock * (int) $price->price),
                0,
                ',',
                '.',
            ),
        );
    }

    public function totalStockFormatted(): Attribute
    {
        return Attribute::make(
            get: function () {
                $total = $this->prices->sum(fn (RawMaterialPrice $price) => (float) $price->stock);
                $formatted = rtrim(rtrim(number_format($total, 4, ',', '.'), '0'), ',');

                return "{$formatted} {$this->unit->abbreviation()}";
            },
        );
    }

    // 5. Relation
    public function ownerVerificationRequests(): MorphMany
    {
        return $this->morphMany(OwnerVerificationRequest::class, 'subject');
    }

    public function pendingOwnerVerificationRequest(): MorphOne
    {
        return $this->morphOne(OwnerVerificationRequest::class, 'subject')
            ->where('status', OwnerVerificationStatus::PENDING)
            ->latestOfMany();
    }

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