<?php

namespace Modules\WhatsApp\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\WhatsApp\Entities\WaAutoReply;
use Modules\WhatsApp\Entities\WaTemplate;

/**
 * CRUD for the chat workflow rules (auto-replies). Evaluated by WorkflowService
 * on every inbound message before the AI.
 */
class WaWorkflowController extends Controller
{
    public function index()
    {
        $this->authorizeManage();
        $businessId = request()->session()->get('user.business_id');

        $rules = WaAutoReply::where('business_id', $businessId)
            ->orderBy('priority')->orderBy('id')->get();
        $templates = WaTemplate::where('business_id', $businessId)->where('active', true)->pluck('name', 'id');

        return view('whatsapp::workflow.index', compact('rules', 'templates'));
    }

    public function store(Request $request)
    {
        $this->authorizeManage();
        $businessId = request()->session()->get('user.business_id');

        $data = $this->validateRule($request);
        $data['business_id'] = $businessId;

        WaAutoReply::create($data);

        return redirect()->route('whatsapp.workflow.index')->with('status', ['success' => 1, 'msg' => __('whatsapp::lang.saved')]);
    }

    public function update(Request $request, $id)
    {
        $this->authorizeManage();
        $businessId = request()->session()->get('user.business_id');

        $rule = WaAutoReply::where('business_id', $businessId)->findOrFail($id);
        $rule->update($this->validateRule($request));

        return redirect()->route('whatsapp.workflow.index')->with('status', ['success' => 1, 'msg' => __('whatsapp::lang.saved')]);
    }

    public function destroy($id)
    {
        $this->authorizeManage();
        $businessId = request()->session()->get('user.business_id');

        WaAutoReply::where('business_id', $businessId)->findOrFail($id)->delete();

        return redirect()->route('whatsapp.workflow.index')->with('status', ['success' => 1, 'msg' => __('whatsapp::lang.saved')]);
    }

    private function validateRule(Request $request): array
    {
        $data = $request->validate([
            'name'        => 'required|string|max:120',
            'trigger'     => 'required|in:welcome,keyword,fallback',
            'keyword'     => 'nullable|string|max:191',
            'match'       => 'required|in:contains,exact,starts',
            'template_id' => 'nullable|integer',
            'body'        => 'nullable|string',
            'priority'    => 'nullable|integer|min:0|max:1000',
        ]);

        $data['stop_after'] = $request->boolean('stop_after');
        $data['active']     = $request->boolean('active');
        $data['priority']   = $data['priority'] ?? 10;

        return $data;
    }

    private function authorizeManage(): void
    {
        if (!auth()->user()->can('whatsapp.manage_templates')) {
            abort(403, 'Unauthorized action.');
        }
    }
}
