<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Concerns\ResolvesPlatformAdminContext;
use App\Http\Controllers\Controller;
use App\Models\Merchant;
use App\Support\CacheKeys;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\View\View;

class MerchantController extends Controller
{
    use ResolvesPlatformAdminContext;

    public function index(Request $request): View
    {
        $this->ensurePlatformAdmin($request);
        $page = max((int) $request->integer('page', 1), 1);

        return view('admin.merchants.index', [
            'merchants' => Cache::remember(
                CacheKeys::platformMerchantsList($page),
                now()->addMinutes(10),
                fn () => Merchant::query()->latest()->paginate(10)->withQueryString()
            ),
            'cacheMeta' => [
                'store' => config('cache.default'),
                'ttl' => '10m',
            ],
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string'],
            'slug' => ['required', 'string'],
            'plan' => ['nullable', 'string'],
            'status' => ['nullable', 'string'],
            'contact_name' => ['nullable', 'string'],
            'contact_phone' => ['nullable', 'string'],
            'contact_email' => ['nullable', 'email'],
        ]);

        Merchant::query()->create([
            'name' => $data['name'],
            'slug' => $data['slug'],
            'plan' => $data['plan'] ?? 'basic',
            'status' => $data['status'] ?? 'active',
            'contact_name' => $data['contact_name'] ?? null,
            'contact_phone' => $data['contact_phone'] ?? null,
            'contact_email' => $data['contact_email'] ?? null,
            'activated_at' => now(),
        ]);

        $this->flushPlatformCaches();

        return redirect('/admin/merchants')->with('success', '商家创建成功');
    }

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

        Cache::forget(CacheKeys::platformDashboardStats());
        Cache::forget(CacheKeys::platformChannelsOverview());
    }
}
