<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\StoreProductRequest;
use App\Http\Requests\Api\UpdateProductRequest;
use App\Http\Resources\Api\ProductResource;
use App\Models\Product;
use App\Services\ActivityLogService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Product::query()->with(['category', 'productImages']);
        if (! $request->user()?->isAdmin()) {
            $query->where('is_active', true);
        }
        if ($request->filled('category_id')) {
            $query->where('category_id', $request->category_id);
        }
        if ($request->filled('search')) {
            $query->where(function ($q) use ($request) {
                $q->where('name', 'like', '%' . $request->search . '%')
                    ->orWhere('description', 'like', '%' . $request->search . '%');
            });
        }
        if ($request->filled('price_min') && is_numeric($request->price_min)) {
            $query->where('price', '>=', (float) $request->price_min);
        }
        if ($request->filled('price_max') && is_numeric($request->price_max)) {
            $query->where('price', '<=', (float) $request->price_max);
        }
        $query->orderBy('name');
        $perPage = min((int) $request->get('per_page', 15), 50);
        $products = $query->paginate($perPage);

        return response()->json([
            'data' => ProductResource::collection($products->items()),
            'meta' => [
                'current_page' => $products->currentPage(),
                'last_page' => $products->lastPage(),
                'per_page' => $products->perPage(),
                'total' => $products->total(),
            ],
        ]);
    }

    public function store(StoreProductRequest $request): JsonResponse
    {
        $data = $request->validated();
        if ($request->hasFile('image')) {
            $data['image'] = $request->file('image')->store('products', 'public');
        }
        $product = Product::create($data);

        $sortOrder = 0;
        foreach ($request->file('images', []) as $file) {
            $product->productImages()->create([
                'path' => $file->store('products', 'public'),
                'sort_order' => $sortOrder++,
            ]);
        }

        ActivityLogService::log(
            'product.created',
            $product,
            ['name' => $product->name, 'price' => $product->price],
            "Produit créé : {$product->name}",
            $request->user()?->id,
            $request
        );

        return response()->json(['data' => new ProductResource($product->load(['category', 'productImages']))], 201);
    }

    public function show(Request $request, Product $product): JsonResponse
    {
        if (! $request->user()?->isAdmin() && ! $product->is_active) {
            abort(404);
        }

        return response()->json(['data' => new ProductResource($product->load(['category', 'productImages']))]);
    }

    public function update(UpdateProductRequest $request, Product $product): JsonResponse
    {
        $data = $request->validated();
        if ($request->hasFile('image')) {
            $data['image'] = $request->file('image')->store('products', 'public');
        }
        $keepIds = $request->validated('keep_secondary_ids', []);
        $product->productImages()->whereNotIn('id', $keepIds)->delete();
        $sortOrder = $product->productImages()->max('sort_order') ?? -1;
        foreach ($request->file('images', []) as $file) {
            $product->productImages()->create([
                'path' => $file->store('products', 'public'),
                'sort_order' => ++$sortOrder,
            ]);
        }
        unset($data['keep_secondary_ids'], $data['images']);
        $oldData = $product->toArray();
        $product->update($data);

        ActivityLogService::log(
            'product.updated',
            $product,
            ['before' => $oldData, 'after' => $product->toArray()],
            "Produit modifié : {$product->name}",
            $request->user()?->id,
            $request
        );

        return response()->json(['data' => new ProductResource($product->fresh()->load(['category', 'productImages']))]);
    }

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

        ActivityLogService::log(
            'product.deleted',
            null,
            ['name' => $name],
            "Produit supprimé : {$name}",
            $request->user()?->id,
            $request
        );

        return response()->json(['message' => __('Product deleted.')]);
    }
}
