<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Location;
use App\Models\Product;
use App\Models\ReplenishmentRule;
use App\Services\LocationService;
use App\Services\ReplenishmentService;
use App\Services\StockTransferService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ReplenishmentController extends Controller
{
    public function __construct(
        protected ReplenishmentService $replenishment,
        protected StockTransferService $transfers,
        protected LocationService $locationService
    ) {
        $this->middleware('auth');
    }

    public function index(Request $request): View
    {
        $user = auth()->user();
        $accessible = $this->locationService->accessibleLocations($user);
        $accessibleIds = $accessible->pluck('id')->all();

        $stores = $accessible->where('type', Location::TYPE_STORE)->values();
        if ($stores->isEmpty()) {
            $stores = $accessible->values();
        }

        // Never list warehouses beyond access - no empty->all fallback
        if ($this->locationService->userCanViewAllLocations($user)) {
            $warehouses = Location::query()->warehouses()->active()->orderBy('name')->get();
        } else {
            $warehouses = $accessible->where('type', Location::TYPE_WAREHOUSE)->values();
        }

        $products = Product::query()
            ->active()
            ->where(function ($q) {
                $q->where(function ($q2) {
                    $q2->whereNull('parent_id')->where('product_type', 'single');
                })->orWhereNotNull('parent_id');
            })
            ->orderBy('name')
            ->limit(500)
            ->get(['id', 'name', 'sku']);

        $storeFilter = $this->locationService->resolveAuthorizedFilterLocationId(
            $user,
            $request->input('store_location_id')
        );

        $rules = ReplenishmentRule::query()
            ->with(['storeLocation', 'warehouseLocation', 'product'])
            ->when(!$this->locationService->userCanViewAllLocations($user), function ($q) use ($accessibleIds) {
                $q->where(function ($q2) use ($accessibleIds) {
                    $q2->whereIn('store_location_id', $accessibleIds)
                        ->orWhereIn('warehouse_location_id', $accessibleIds);
                });
            })
            ->when($storeFilter, fn ($q) => $q->where('store_location_id', $storeFilter))
            ->latest()
            ->paginate(30);

        $suggestions = $this->replenishment->suggestions($storeFilter)->take(50);

        return view('admin.replenishment.index', compact('rules', 'stores', 'warehouses', 'products', 'suggestions', 'storeFilter'));
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'store_location_id' => 'required|exists:locations,id',
            'warehouse_location_id' => 'required|exists:locations,id|different:store_location_id',
            'product_id' => 'nullable|exists:products,id',
            'min_qty' => 'required|integer|min:0',
            'max_qty' => 'required|integer|min:0',
            'reorder_qty' => 'required|integer|min:0',
            'is_active' => 'nullable|boolean',
        ]);

        $user = auth()->user();
        $this->locationService->resolveAuthorizedLocationId($user, $data['store_location_id']);

        ReplenishmentRule::create([
            ...$data,
            'is_active' => $request->boolean('is_active', true),
        ]);

        return back()->with('success', 'Replenishment rule saved.');
    }

    public function destroy(ReplenishmentRule $replenishment): RedirectResponse
    {
        $user = auth()->user();
        if (!$this->locationService->userCanViewAllLocations($user)) {
            $this->locationService->resolveAuthorizedLocationId($user, $replenishment->store_location_id);
        }
        $replenishment->delete();

        return back()->with('success', 'Rule deleted.');
    }

    public function createTransferFromSuggestions(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'warehouse_location_id' => 'required|exists:locations,id',
            'store_location_id' => 'required|exists:locations,id|different:warehouse_location_id',
            'items' => 'required|array|min:1',
            'items.*.product_id' => 'required|exists:products,id',
            'items.*.quantity' => 'required|integer|min:1',
        ]);

        $user = auth()->user();
        $this->locationService->assertCanCreateTransfer(
            $user,
            (int) $data['warehouse_location_id'],
            (int) $data['store_location_id']
        );

        $transfer = $this->transfers->create(
            (int) $data['warehouse_location_id'],
            (int) $data['store_location_id'],
            $data['items'],
            'Auto-created from replenishment suggestions'
        );

        return redirect()
            ->route('admin.transfers.show', $transfer)
            ->with('success', 'Transfer draft created from replenishment suggestions.');
    }
}
