<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Rule;
use Illuminate\Http\Request;

class RuleController extends Controller
{
    public function index(Request $request)
    {
        return Rule::where('tenant_id', $request->user()->tenant_id)->orderBy('priority')->paginate(25);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => ['required', 'string'],
            'module' => ['required', 'string'],
            'priority' => ['required', 'integer'],
            'conditions' => ['required', 'array'],
            'actions' => ['required', 'array'],
            'is_active' => ['boolean'],
        ]);

        $data['tenant_id'] = $request->user()->tenant_id;

        return Rule::create($data);
    }

    public function show(Request $request, Rule $rule)
    {
        abort_unless($rule->tenant_id === $request->user()->tenant_id, 404);

        return $rule;
    }

    public function update(Request $request, Rule $rule)
    {
        abort_unless($rule->tenant_id === $request->user()->tenant_id, 404);
        $rule->update($request->all());

        return $rule->fresh();
    }

    public function destroy(Request $request, Rule $rule)
    {
        abort_unless($rule->tenant_id === $request->user()->tenant_id, 404);
        $rule->delete();

        return response()->noContent();
    }
}
