<?php

namespace App\Domain\Inventory\Models;

use App\Domain\Inventory\Enums\ProductType;
use App\Domain\Shared\Traits\Auditable;
use App\Domain\Shared\Traits\BelongsToAcademy;
use App\Domain\Shared\Traits\HasUuid;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Product extends Model
{
    use BelongsToAcademy, HasUuid, SoftDeletes, Auditable;

    protected $fillable = [
        'academy_id',
        'category_id',
        'branch_id',
        'sku',
        'barcode',
        'name_ar',
        'name',
        'description_ar',
        'type',
        'unit',
        'selling_price',
        'cost_price',
        'track_inventory',
        'is_active',
        'min_stock_level',
        'max_stock_level',
        'weight_grams',
        'dimensions',
        'photo_path',
        'tax_rate',
        'sort_order',
        'created_by',
        'metadata',
    ];

    protected function casts(): array
    {
        return [
            'type' => ProductType::class,
            'selling_price' => 'integer',
            'cost_price' => 'integer',
            'track_inventory' => 'boolean',
            'is_active' => 'boolean',
            'min_stock_level' => 'integer',
            'max_stock_level' => 'integer',
            'weight_grams' => 'integer',
            'dimensions' => 'array',
            'tax_rate' => 'integer',
            'sort_order' => 'integer',
            'metadata' => 'array',
        ];
    }

    public function category(): BelongsTo
    {
        return $this->belongsTo(ProductCategory::class, 'category_id');
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(\App\Domain\Identity\Models\Branch::class);
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

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

    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true);
    }

    public function scopeTracked(Builder $query): Builder
    {
        return $query->where('track_inventory', true);
    }

    public function scopeByCategory(Builder $query, int $categoryId): Builder
    {
        return $query->where('category_id', $categoryId);
    }
}
