<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Strategy;
use App\Models\SystemLog;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AdminRulebookController extends Controller
{
    public function edit(): View
    {
        $strategy = Strategy::whereHas('user', fn ($q) => $q->where('role', 'admin'))->first();

        return view('admin.rulebook', [
            'pageTitle' => 'Rulebook Editor',
            'pageSubtitle' => 'Default strategy template for new users',
            'rulebook' => json_encode($strategy?->rulebook ?? config('rulebook'), JSON_PRETTY_PRINT),
        ]);
    }

    public function update(Request $request): RedirectResponse
    {
        $request->validate(['rulebook' => 'required|json']);

        $decoded = json_decode($request->input('rulebook'), true);
        Strategy::whereHas('user', fn ($q) => $q->where('role', 'admin'))->update(['rulebook' => $decoded]);

        SystemLog::create([
            'channel' => 'admin',
            'level' => 'info',
            'message' => 'Default rulebook updated',
        ]);

        return back()->with('status', 'Rulebook updated.');
    }
}
