<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Models\BusinessRule;
use App\Models\DevelopmentScope;
use App\Support\ActivityLogger;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class BusinessRuleController extends Controller
{
    public function index(): View
    {
        return view('app.settings.business-rules', [
            'rules' => BusinessRule::with(['modules', 'relationships'])->orderBy('rule_code')->get(),
        ]);
    }

    public function map(BusinessRule $businessRule): View
    {
        return view('app.settings.business-rule-map', [
            'rule' => $businessRule->load(['modules', 'relationships', 'versions']),
        ]);
    }

    public function generateScope(Request $request, BusinessRule $businessRule): RedirectResponse
    {
        $scope = DevelopmentScope::create([
            'business_rule_id' => $businessRule->id,
            'title' => 'Scope for '.$businessRule->rule_code.' '.$businessRule->title,
            'impacted_modules' => $businessRule->modules->pluck('module_name')->all(),
            'impacted_roles' => $businessRule->affected_roles,
            'impacted_tables' => $businessRule->affected_tables,
            'acceptance_criteria' => [
                'Updated rule is reflected in application behavior',
                'Access control is covered by feature tests',
            ],
            'test_cases' => [
                'Role with access behaves as expected',
                'Role without access is blocked',
            ],
            'priority' => 'medium',
            'status' => 'draft',
            'estimate_placeholder' => 'TBD after technical review',
        ]);

        ActivityLogger::log('development_scope.created', $request->user(), $scope, [], $scope->toArray(), $request);

        return back()->with('success', 'Development scope generated.');
    }
}
