<?php

namespace App\Http\Controllers\Admin\Master;

use App\Enums\Permission;
use App\Http\Controllers\Concerns\FlashesEntityMessage;
use App\Http\Controllers\Concerns\ParsesDataTableQuery;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Master\ProductRequest;
use App\Http\Requests\Admin\ToggleStatusRequest;
use App\Models\Product;
use App\Services\Master\CategoryService;
use App\Services\Master\ProductService;
use App\Support\Media\MediaPresenter;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class ProductController extends Controller
{
    use FlashesEntityMessage, ParsesDataTableQuery;

    public function __construct(
        private readonly ProductService $productService,
        private readonly CategoryService $categoryService,
    ) {}

    public function index(Request $request): Response
    {
        $tableQuery = $this->parseDataTableQuery($request);
        $tableQuery['search_id'] = $request->string('search_id')->trim()->toString();
        $status = $request->string('status')->toString();
        $categoryId = $request->string('category_id')->toString();
        $stockStatus = $request->string('stock_status')->toString();
        $productId = $request->string('product_id')->toString();

        return Inertia::render('admin/master/products/Index', [
            'products' => $this->productService->paginateForIndex($tableQuery, $status, $categoryId, $stockStatus, $productId),
            'categories' => $this->categoryService->getSelectOptions(),
            'filters' => $this->dataTableFilters($tableQuery, [
                'status' => $status,
                'category_id' => $categoryId,
                'stock_status' => $stockStatus,
                'search_id' => $tableQuery['search_id'],
                'product_id' => $productId,
            ]),
            'productsList' => Product::query()->orderBy('name')->get(['id', 'name'])->map(fn ($p) => ['value' => (string) $p->id, 'label' => $p->name])->all(),
        ]);
    }

    public function create(): Response
    {
        return Inertia::render('admin/master/products/Create', [
            'categories' => $this->categoryService->getSelectOptions(),
        ]);
    }

    public function store(ProductRequest $request): RedirectResponse
    {
        $this->productService->create($request->validated(), $request->user());

        if ($request->user()->can(Permission::OWNER_VERIFICATIONS_VERIFY->value)) {
            $this->flashCreated('Produk');
        } else {
            $this->flashSuccess('Produk berhasil diajukan dan menunggu verifikasi owner.');
        }

        return redirect()->route('admin.master.products.index');
    }

    public function edit(Product $product): Response
    {
        return Inertia::render('admin/master/products/Edit', [
            'categories' => $this->categoryService->getSelectOptions(),
            'product' => $this->productService->findForEdit($product),
        ]);
    }

    public function update(ProductRequest $request, Product $product): RedirectResponse
    {
        $this->productService->update($product, $request->validated(), $request->user());

        if ($request->user()->can(Permission::OWNER_VERIFICATIONS_VERIFY->value)) {
            $this->flashUpdated('Produk');
        } else {
            $this->flashSuccess('Perubahan produk berhasil diajukan dan menunggu verifikasi owner.');
        }

        return redirect()->route('admin.master.products.index');
    }

    public function destroy(Request $request, Product $product): RedirectResponse
    {
        $this->productService->delete($product, $request->user());

        if ($request->user()->can(Permission::OWNER_VERIFICATIONS_VERIFY->value)) {
            $this->flashDeleted('Produk');
        } else {
            $this->flashSuccess('Penghapusan produk berhasil diajukan dan menunggu verifikasi owner.');
        }

        return redirect()->route('admin.master.products.index');
    }

    public function toggleStatus(ToggleStatusRequest $request, Product $product): RedirectResponse
    {
        $this->productService->toggleStatus($product, $request->validated(), $request->user());

        if ($request->user()->can(Permission::OWNER_VERIFICATIONS_VERIFY->value)) {
            $this->flashStatusUpdated('produk');
        } else {
            $this->flashSuccess('Perubahan status produk berhasil diajukan dan menunggu verifikasi owner.');
        }

        return back();
    }

    public function show(Product $product): JsonResponse
    {
        $product->load([
            'categories',
            'variants' => fn ($query) => $query
                ->with(['media', 'prices'])
                ->orderBy('created_at'),
        ]);

        $product->variants->each(function ($variant): void {
            $variant->setAttribute('images', MediaPresenter::collection($variant, 'images'));
        });

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