<?php

namespace App\Domains\Catalog\Controllers;

use App\Domains\Catalog\Models\Product;
use App\Domains\Catalog\Requests\StoreProductRequest;
use App\Domains\Catalog\Requests\UpdateProductRequest;
use App\Domains\Catalog\Resources\ProductResource;
use App\Domains\Catalog\Services\ProductService;
use App\Domains\Tenant\Models\Tenant;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class ProductController extends Controller
{
    public function index(Tenant $tenant): JsonResponse
    {
        return ProductResource::collection(
            Product::query()
                ->where('tenant_codigo', $tenant->codigo)
                ->with([
                    'attachments' => fn ($query) => $query->orderBy('attachments.id')->limit(1),
                    'brand',
                    'category',
                ])
                ->latest()
                ->paginateFromRequest()
        )->response();
    }

    public function store(StoreProductRequest $request, Tenant $tenant, ProductService $productService): JsonResponse
    {
        $product = $productService->create($tenant, $request->validated());

        return ProductResource::make($product)->response()->setStatusCode(201);
    }

    public function show(Tenant $tenant, Product $producto): ProductResource
    {
        $producto = $this->resolveScopedProduct($tenant, $producto);

        return ProductResource::make($producto->load([
            'attachments',
            'brand',
            'category',
            'variants.definitions.attribute.options',
            'variants.attachments',
        ]));
    }

    public function update(UpdateProductRequest $request, Tenant $tenant, Product $producto, ProductService $productService): ProductResource
    {
        $producto = $this->resolveScopedProduct($tenant, $producto);
        $producto = $productService->update($producto, $request->validated());

        return ProductResource::make($producto);
    }

    public function destroy(Tenant $tenant, Product $producto, ProductService $productService): Response
    {
        $producto = $this->resolveScopedProduct($tenant, $producto);
        $productService->delete($producto);

        return response()->noContent();
    }

    protected function resolveScopedProduct(Tenant $tenant, Product $product): Product
    {
        if ($product->tenant_codigo !== $tenant->codigo) {
            throw new NotFoundHttpException('Product not found for tenant.');
        }

        return $product;
    }
}
