<?php

namespace App\Http\Controllers\MerchantAdmin;

use App\Http\Controllers\Concerns\ResolvesMerchantContext;
use App\Http\Controllers\Controller;
use App\Models\ProductCategory;
use App\Support\CacheKeys;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class ProductCategoryController extends Controller
{
    use ResolvesMerchantContext;

    public function index(Request $request): View
    {
        $merchantId = $this->merchantId($request);

        $page = max((int) $request->integer('page', 1), 1);

        return view('merchant_admin.product_categories.index', [
            'categories' => Cache::remember(
                CacheKeys::merchantCategoriesList($merchantId, $page),
                now()->addMinutes(10),
                fn () => ProductCategory::query()->forMerchant($merchantId)->orderBy('sort')->orderBy('id')->paginate(10)->withQueryString()
            ),
            'cacheMeta' => [
                'store' => config('cache.default'),
                'ttl' => '10m',
            ],
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $merchantId = $this->merchantId($request);

        $data = $request->validate([
            'name' => ['required', 'string'],
            'slug' => [
                'required',
                'string',
                Rule::unique('product_categories', 'slug')->where(fn ($query) => $query->where('merchant_id', $merchantId)),
            ],
            'status' => ['nullable', 'string'],
            'sort' => ['nullable', 'integer'],
            'description' => ['nullable', 'string'],
        ], [
            'slug.unique' => '当前商家下该分类 slug 已存在，请换一个。',
        ]);

        ProductCategory::query()->create([
            'merchant_id' => $merchantId,
            'name' => $data['name'],
            'slug' => $data['slug'],
            'status' => $data['status'] ?? 'active',
            'sort' => $data['sort'] ?? 0,
            'description' => $data['description'] ?? null,
        ]);

        $this->flushMerchantCaches($merchantId);

        return redirect('/merchant-admin/product-categories')->with('success', '商品分类创建成功');
    }

    public function update(Request $request, int $id): RedirectResponse
    {
        $merchantId = $this->merchantId($request);

        $category = ProductCategory::query()->forMerchant($merchantId)->findOrFail($id);

        $data = $request->validate([
            'name' => ['required', 'string'],
            'slug' => [
                'nullable',
                'string',
                Rule::unique('product_categories', 'slug')->where(fn ($query) => $query->where('merchant_id', $merchantId))->ignore($category->id),
            ],
            'status' => ['required', 'string'],
            'sort' => ['nullable', 'integer'],
            'description' => ['nullable', 'string'],
        ], [
            'slug.unique' => '当前商家下该分类 slug 已存在，请换一个。',
        ]);
        $category->update([
            'name' => $data['name'],
            'slug' => $data['slug'] ?? $category->slug,
            'status' => $data['status'],
            'sort' => $data['sort'] ?? 0,
            'description' => $data['description'] ?? null,
        ]);

        $this->flushMerchantCaches($merchantId);

        return redirect('/merchant-admin/product-categories')->with('success', '商品分类更新成功');
    }

    public function destroy(Request $request, int $id): RedirectResponse
    {
        $merchantId = $this->merchantId($request);

        $category = ProductCategory::query()->forMerchant($merchantId)->findOrFail($id);
        $category->delete();

        $this->flushMerchantCaches($merchantId);

        return redirect('/merchant-admin/product-categories')->with('success', '商品分类删除成功');
    }

    protected function flushMerchantCaches(int $merchantId): void
    {
        for ($page = 1; $page <= 5; $page++) {
            Cache::forget(CacheKeys::merchantProductsList($merchantId, $page));
            Cache::forget(CacheKeys::merchantCategoriesList($merchantId, $page));
        }

        Cache::forget(CacheKeys::merchantDashboardStats($merchantId));
    }
}
