<?php

namespace App\Http\Controllers\Api\Seller;

use App\Http\Controllers\Controller;
use App\Jobs\ProcessStockAlerts;
use App\Models\Product;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ProductController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $store = $request->user()->store;

        if (!$store) {
            return response()->json(['message' => 'Mağazanız bulunamadı.'], 404);
        }

        $query = $store->products()->with('category');

        if ($request->has('category_id')) {
            $query->where('category_id', $request->category_id);
        }

        if ($request->has('is_active')) {
            $query->where('is_active', filter_var($request->is_active, FILTER_VALIDATE_BOOLEAN));
        }

        if ($request->has('search')) {
            $query->where('name', 'like', '%' . $request->search . '%');
        }

        $products = $query->orderBy('created_at', 'desc')->paginate(20);

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

    public function store(Request $request): JsonResponse
    {
        $store = $request->user()->store;

        if (!$store) {
            return response()->json(['message' => 'Mağazanız bulunamadı.'], 404);
        }

        $validated = $request->validate([
            'category_id' => 'required|exists:product_categories,id',
            'name' => 'required|string|max:255',
            'description' => 'nullable|string|max:1000',
            'stock_quantity' => 'required|integer|min:0',
            'price' => 'required|numeric|min:0|max:99999999.99',
            'unit_type' => 'required|in:adet,paket,kg,kutu',
            'is_active' => 'boolean',
        ]);

        $validated['store_id'] = $store->id;

        if ($request->hasFile('image')) {
            $request->validate(['image' => 'image|mimes:jpeg,png,jpg,webp|max:2048']);
            $validated['image'] = $request->file('image')->store('products', 'public');
        }

        $product = Product::create($validated);
        $product->load('category');

        return response()->json([
            'message' => 'Ürün başarıyla eklendi.',
            'data' => $product,
        ], 201);
    }

    public function show(Request $request, Product $product): JsonResponse
    {
        $store = $request->user()->store;

        if (!$store || $product->store_id !== $store->id) {
            return response()->json(['message' => 'Ürün bulunamadı.'], 404);
        }

        $product->load('category');

        return response()->json(['data' => $product]);
    }

    public function update(Request $request, Product $product): JsonResponse
    {
        $store = $request->user()->store;

        if (!$store || $product->store_id !== $store->id) {
            return response()->json(['message' => 'Bu ürünü düzenleme yetkiniz yok.'], 403);
        }

        $validated = $request->validate([
            'category_id' => 'sometimes|required|exists:product_categories,id',
            'name' => 'sometimes|required|string|max:255',
            'description' => 'nullable|string|max:1000',
            'stock_quantity' => 'sometimes|integer|min:0',
            'price' => 'sometimes|required|numeric|min:0|max:99999999.99',
            'unit_type' => 'sometimes|required|in:adet,paket,kg,kutu',
            'is_active' => 'boolean',
        ]);

        if ($request->hasFile('image')) {
            $request->validate(['image' => 'image|mimes:jpeg,png,jpg,webp|max:2048']);
            if ($product->image) {
                Storage::disk('public')->delete($product->image);
            }
            $validated['image'] = $request->file('image')->store('products', 'public');
        }

        $oldStock = $product->stock_quantity;
        $product->update($validated);

        if (isset($validated['stock_quantity']) && $validated['stock_quantity'] > $oldStock && $validated['stock_quantity'] > 0) {
            ProcessStockAlerts::dispatch($product->fresh());
        }

        $product->load('category');

        return response()->json([
            'message' => 'Ürün güncellendi.',
            'data' => $product,
        ]);
    }

    public function updateStock(Request $request, Product $product): JsonResponse
    {
        $store = $request->user()->store;

        if (!$store || $product->store_id !== $store->id) {
            return response()->json(['message' => 'Bu ürünü güncelleme yetkiniz yok.'], 403);
        }

        $validated = $request->validate([
            'stock_quantity' => 'required|integer|min:0',
        ]);

        $oldStock = $product->stock_quantity;
        $product->update($validated);

        if ($validated['stock_quantity'] > $oldStock && $validated['stock_quantity'] > 0) {
            ProcessStockAlerts::dispatch($product->fresh());
        }

        return response()->json([
            'message' => 'Stok güncellendi.',
            'data' => [
                'stock_quantity' => $product->stock_quantity,
                'stock_label' => $product->stock_label,
            ],
        ]);
    }

    public function destroy(Request $request, Product $product): JsonResponse
    {
        $store = $request->user()->store;

        if (!$store || $product->store_id !== $store->id) {
            return response()->json(['message' => 'Bu ürünü silme yetkiniz yok.'], 403);
        }

        if ($product->image) {
            Storage::disk('public')->delete($product->image);
        }

        $product->delete();

        return response()->json(['message' => 'Ürün silindi.']);
    }
}
