<?php

namespace App\Services\Manufacturing;

use App\Services\BaseService;
use App\Repositories\SkuRepository;
use App\Models\SkuMaster;
use App\Models\SkuMovement;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class SkuService extends BaseService
{
    protected SkuRepository $skuRepository;

    public function __construct(SkuRepository $repository)
    {
        parent::__construct($repository);
        $this->skuRepository = $repository;
    }

    /**
     * Get SKUs with category
     */
    public function getAllWithCategory(): Collection
    {
        return $this->skuRepository->getWithCategory();
    }

    /**
     * Get SKUs by category
     */
    public function getByCategory(int $categoryId): Collection
    {
        return $this->skuRepository->getByCategory($categoryId);
    }

    /**
     * Get active SKUs
     */
    public function getActive(): Collection
    {
        return $this->skuRepository->getActive();
    }

    /**
     * Search SKUs
     */
    public function search(string $term): Collection
    {
        return $this->skuRepository->search($term);
    }

    /**
     * Get low stock SKUs
     */
    public function getLowStock(int $threshold = 10): Collection
    {
        return $this->skuRepository->getLowStock($threshold);
    }

    /**
     * Generate SKU code
     */
    public function generateSkuCode(): string
    {
        return nextNumber('SKU', 'sku_masters', 'sku_code', 1);
    }

    /**
     * Create SKU with initial stock
     */
    public function createWithStock(array $data): SkuMaster
    {
        return DB::transaction(function () use ($data) {
            $data['sku_code'] = $data['sku_code'] ?? $this->generateSkuCode();
            $sku = $this->create($data);

            if (($data['quantity'] ?? 0) > 0) {
                $this->recordMovement($sku->id, 'in', $data['quantity'], 'Initial stock');
            }

            $this->logAction('SKU created', ['id' => $sku->id]);
            return $sku;
        });
    }

    /**
     * Record stock movement
     */
    public function recordMovement(int $skuId, string $type, float $quantity, ?string $remarks = null): SkuMovement
    {
        return DB::transaction(function () use ($skuId, $type, $quantity, $remarks) {
            $sku = $this->findByIdOrFail($skuId);

            $movement = SkuMovement::create([
                'sku_master_id' => $skuId,
                'movement_type' => $type,
                'quantity' => $quantity,
                'remarks' => $remarks,
                'created_by' => auth()->id(),
            ]);

            // Update SKU quantity
            if ($type === 'in') {
                $sku->increment('quantity', $quantity);
            } else {
                $sku->decrement('quantity', $quantity);
            }

            return $movement;
        });
    }

    /**
     * Get movements for SKU
     */
    public function getMovements(int $skuId): Collection
    {
        return SkuMovement::where('sku_master_id', $skuId)
            ->orderBy('created_at', 'desc')
            ->get();
    }
}
