<?php

namespace App\Repositories;

use App\Models\SkuMaster;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;

class SkuRepository extends BaseRepository
{
    protected function resolveModel(): Model
    {
        return new SkuMaster();
    }

    /**
     * Get all SKUs with category
     */
    public function getWithCategory(): Collection
    {
        return $this->with(['category'])
            ->orderBy('sku_code', 'asc')
            ->all();
    }

    /**
     * Get SKUs by category
     */
    public function getByCategory(int $categoryId): Collection
    {
        return $this->where('category_id', $categoryId)->all();
    }

    /**
     * Get active SKUs
     */
    public function getActive(): Collection
    {
        return $this->where('status', 'active')
            ->orderBy('sku_code', 'asc')
            ->all();
    }

    /**
     * Search SKUs by code or name
     */
    public function search(string $term): Collection
    {
        $query = $this->getQuery();
        $query->where(function ($q) use ($term) {
            $q->where('sku_code', 'like', "%{$term}%")
                ->orWhere('name', 'like', "%{$term}%");
        });
        $result = $query->get();
        $this->resetQuery();
        return $result;
    }

    /**
     * Get low stock SKUs
     */
    public function getLowStock(int $threshold = 10): Collection
    {
        return $this->where('quantity', '<=', $threshold)
            ->where('status', 'active')
            ->orderBy('quantity', 'asc')
            ->all();
    }
}
