<?php

namespace App\Models;

use App\Enums\OwnerVerificationStatus;
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\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Sluggable\Attributes\Sluggable;

/**
 * @method static \Illuminate\Database\Eloquent\Builder active()
 * @method static \Illuminate\Database\Eloquent\Builder inactive()
 */
#[Guarded(['id'])]
#[Appends(['total_stock_formatted', 'total_reject_stock_formatted', 'total_retail_stock_formatted'])]
#[Sluggable(from: 'name', to: 'slug')]
class Product extends Model
{
    // 1. Use Trait
    use HasFactory, HasPendingOwnerVerification, InteractsWithActivityLog, SoftDeletes;

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

    // 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 totalRejectStockFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => number_format($this->variants->sum('reject_stock'), 0, ',', '.'),
        );
    }

    public function totalRetailStockFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => number_format($this->variants->sum('retail_stock'), 0, ',', '.'),
        );
    }

    public function totalStockFormatted(): Attribute
    {
        return Attribute::make(
            get: fn () => number_format($this->variants->sum('stock'), 0, ',', '.'),
        );
    }

    // 5. Other Methods
    public static function getActiveWithVariantsAndCategories(): Collection
    {
        return self::query()
            ->active()
            ->with([
                'categories',
                'variants' => fn ($query) => $query
                    ->with('media')
                    ->orderBy('created_at'),
            ])
            ->get();
    }

    // 6. Relation
    public function categories(): BelongsToMany
    {
        return $this->belongsToMany(Category::class, 'product_categories');
    }

    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 variants(): HasMany
    {
        return $this->hasMany(ProductVariant::class);
    }
}
