<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\InventoryAdjustment;
use App\Models\Product;
use App\Services\ActivityLogger;
use App\Services\NotificationService;
use App\Services\ProductService;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class InventoryAdjustmentController extends Controller
{
    public function __construct(protected ProductService $productService) {}
    public function index(Request $request)
    {
        $query = InventoryAdjustment::with(['product', 'user'])
            ->orderBy('created_at', 'desc');

        // Filter by product
        if ($request->filled('product_id')) {
            $query->where('product_id', $request->product_id);
        }

        // Filter by type
        if ($request->filled('type')) {
            $query->where('type', $request->type);
        }

        // Filter by date range
        if ($request->filled('start_date')) {
            $query->whereDate('created_at', '>=', $request->start_date);
        }

        if ($request->filled('end_date')) {
            $query->whereDate('created_at', '<=', $request->end_date);
        }

        $adjustments = $query->paginate($request->per_page ?? 15);

        return response()->json($adjustments);
    }

    public function store(Request $request)
    {
        $this->authorize('manage-inventory');

        $validated = $request->validate([
            'product_id' => ['required', Rule::exists('products', 'id')->where('organization_id', app('current_organization_id'))],
            'type' => 'required|in:add,subtract,set',
            'quantity_adjusted' => 'required|integer|min:1',
            'reason' => 'required|string|max:500',
        ]);

        try {
            $product = Product::findOrFail($validated['product_id']);

            // Delegate to ProductService which correctly updates both
            // product_stocks (branch-specific) AND products.stock_quantity (aggregate).
            $adjustment = $this->productService->adjustStock(
                $product,
                $validated['quantity_adjusted'],
                $validated['type'],
                $validated['reason'],
                $request->user()->id
            );

            $quantityBefore = $adjustment->quantity_before;
            $quantityAfter  = $adjustment->quantity_after;

            ActivityLogger::log(
                'stock_adjusted',
                "Stock adjusted for '{$product->name}': {$quantityBefore} → {$quantityAfter} ({$validated['type']}) — {$validated['reason']}",
                $product,
                ['stock_quantity' => $quantityBefore],
                ['stock_quantity' => $quantityAfter]
            );

            $orgId    = app('current_organization_id');
            $branchId = app()->bound('current_branch_id') ? app('current_branch_id') : null;
            $actorId  = $request->user()->id;

            // Low stock alert if quantity dropped below threshold
            $threshold = (int) ($product->low_stock_threshold ?? 10);
            if ($quantityAfter <= $threshold && $quantityAfter < $quantityBefore) {
                NotificationService::notifyRoles(
                    $orgId,
                    $branchId,
                    ['admin', 'manager'],
                    'low_stock',
                    'Low Stock Alert — ' . $product->name,
                    "Stock for \"{$product->name}\" has dropped to {$quantityAfter} unit(s) (threshold: {$threshold}).",
                    ['product_id' => $product->id, 'product_name' => $product->name, 'quantity' => $quantityAfter, 'threshold' => $threshold],
                    $actorId
                );
            }

            return response()->json(
                $adjustment->load(['product', 'user']),
                201
            );
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Failed to create adjustment: ' . $e->getMessage()
            ], 422);
        }
    }

    public function show(InventoryAdjustment $inventoryAdjustment)
    {
        return response()->json(
            $inventoryAdjustment->load(['product', 'user'])
        );
    }

    public function destroy(InventoryAdjustment $inventoryAdjustment)
    {
        $this->authorize('manage-inventory');

        return response()->json([
            'message' => 'Inventory adjustments cannot be deleted for audit purposes'
        ], 403);
    }

    public function history(Request $request, $productId)
    {
        $adjustments = InventoryAdjustment::with(['user'])
            ->where('product_id', $productId)
            ->orderBy('created_at', 'desc')
            ->limit($request->limit ?? 20)
            ->get();

        return response()->json($adjustments);
    }
}
