<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Concerns\ResolvesPlatformAdminContext;
use App\Http\Controllers\Controller;
use App\Models\ProductCategory;
use App\Models\Merchant;
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 ResolvesPlatformAdminContext;

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

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

        return view('admin.product_categories.index', [
            'categories' => Cache::remember(
                CacheKeys::platformCategoriesList($page),
                now()->addMinutes(10),
                fn () => ProductCategory::query()->with('merchant')->orderBy('merchant_id')->orderBy('sort')->orderBy('id')->paginate(10)->withQueryString()
            ),
            'merchants' => Merchant::query()->orderBy('id')->get(),
            'cacheMeta' => [
                'store' => config('cache.default'),
                'ttl' => '10m',
            ],
        ]);
    }

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

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

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

        $this->flushPlatformCaches();

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

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

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

        $data = $request->validate([
            'name' => ['required', 'string'],
            'slug' => [
                'nullable',
                'string',
                Rule::unique('product_categories', 'slug')->where(fn ($query) => $query->where('merchant_id', $category->merchant_id))->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->flushPlatformCaches();

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

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

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

        $this->flushPlatformCaches();

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

    protected function flushPlatformCaches(): void
    {
        for ($page = 1; $page <= 5; $page++) {
            Cache::forget(CacheKeys::platformProductsList($page));
            Cache::forget(CacheKeys::platformCategoriesList($page));
        }
    }
}
