<?php

namespace App\Http\Controllers\Admin;

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

class DisciplineScoreRuleController extends Controller
{
    public function index(): View
    {
        DisciplineScoreRule::seedDefaults();

        return view('admin.discipline-score-rules.index', [
            'rules' => DisciplineScoreRule::orderBy('sort_order')->orderBy('name')->get(),
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        DisciplineScoreRule::create($this->validated($request));

        return back()->with('success', 'Discipline score rule created.');
    }

    public function update(Request $request, DisciplineScoreRule $disciplineScoreRule): RedirectResponse
    {
        $disciplineScoreRule->update($this->validated($request));

        return back()->with('success', 'Discipline score rule updated.');
    }

    public function destroy(DisciplineScoreRule $disciplineScoreRule): RedirectResponse
    {
        $disciplineScoreRule->delete();

        return back()->with('success', 'Discipline score rule deleted.');
    }

    private function validated(Request $request): array
    {
        $data = $request->validate([
            'key' => ['required', 'string', 'max:100'],
            'name' => ['required', 'string', 'max:255'],
            'points' => ['required', 'integer', 'min:0', 'max:100'],
            'sort_order' => ['required', 'integer', 'min:0', 'max:9999'],
            'is_active' => ['nullable', 'boolean'],
        ]);
        $data['is_active'] = $request->boolean('is_active');

        return $data;
    }
}
