<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\Service;
use App\Models\WorkflowStage;
use App\Models\WorkflowTransition;
use App\Services\UaeTypingCenterWorkflowService;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class WorkflowBuilderController extends Controller
{
    public function storeStage(Request $request, $serviceId)
    {
        $tenantId = auth()->user()->tenant_id;
        $service = Service::where('tenant_id', $tenantId)->findOrFail($serviceId);
        $validated = $request->validate([
            'stage_code' => ['required', 'alpha_dash', 'max:60', Rule::unique('workflow_stages')->where('service_id', $service->id)],
            'stage_name_en' => 'required|string|max:180',
            'stage_name_ar' => 'nullable|string|max:180',
            'stage_type' => ['required', Rule::in(['start', 'verification', 'internal_processing', 'government_submission', 'payment', 'approval', 'completion', 'rejection'])],
            'display_order' => 'required|integer|min:1|max:9999',
            'sla_minutes' => 'required|integer|min:0|max:525600',
            'queue_role' => 'nullable|string|max:80',
            'instructions' => 'nullable|string|max:2000',
        ]);

        $stage = WorkflowStage::create([
            'tenant_id' => $tenantId,
            'service_id' => $service->id,
        ] + $validated + [
            'requires_documents' => $request->boolean('requires_documents'),
            'requires_payment' => $request->boolean('requires_payment'),
            'requires_approval' => $request->boolean('requires_approval'),
            'requires_submission' => $request->boolean('requires_submission'),
            'requires_output' => $request->boolean('requires_output'),
            'requires_notification' => $request->boolean('requires_notification'),
            'can_skip' => $request->boolean('can_skip'),
            'can_reopen' => $request->boolean('can_reopen'),
            'is_customer_visible' => $request->boolean('is_customer_visible', true),
        ]);
        AuditLog::record('services', 'workflow.stage_created', $stage);

        return back()->with('status', 'Workflow stage added.');
    }

    public function storeTransition(Request $request, $serviceId)
    {
        $validated = $request->validate([
            'from_stage_id' => 'required|integer|different:to_stage_id',
            'to_stage_id' => 'required|integer',
            'action_name_en' => 'required|string',
            'action_name_ar' => 'nullable|string|max:180',
            'required_permission' => 'nullable|exists:permissions,slug',
            'payment_requirement' => ['nullable', Rule::in(['none', 'full', 'deposit', 'government_fee', 'full_or_credit'])],
            'target_application_status' => 'nullable|string|max:80',
        ]);

        $tenantId = auth()->user()->tenant_id;
        $service = Service::where('tenant_id', $tenantId)->findOrFail($serviceId);
        $fromStage = WorkflowStage::where('tenant_id', $tenantId)->where('service_id', $service->id)->findOrFail($validated['from_stage_id']);
        $toStage = WorkflowStage::where('tenant_id', $tenantId)->where('service_id', $service->id)->findOrFail($validated['to_stage_id']);

        $transition = WorkflowTransition::create([
            'tenant_id' => $tenantId,
            'service_id' => $service->id,
            'from_stage_id' => $fromStage->id,
            'to_stage_id' => $toStage->id,
            'action_name_en' => $validated['action_name_en'],
            'action_name_ar' => $validated['action_name_ar'] ?? null,
            'required_permission' => $validated['required_permission'] ?? null,
            'payment_requirement' => $validated['payment_requirement'] ?? 'none',
            'target_application_status' => $validated['target_application_status'] ?? null,
            'requires_approval' => $request->boolean('requires_approval'),
            'creates_task' => $request->boolean('creates_task', true),
            'is_return_path' => $request->boolean('is_return_path'),
        ]);
        AuditLog::record('services', 'workflow.transition_created', $transition);

        return back()->with('status', 'Workflow transition rule added.');
    }

    public function installUaeWorkflow($serviceId, UaeTypingCenterWorkflowService $workflowService)
    {
        $service = Service::where('tenant_id', auth()->user()->tenant_id)->findOrFail($serviceId);
        $summary = $workflowService->ensureForService($service, true);
        AuditLog::record('services', 'workflow.uae_template_installed', $service);

        return back()->with('status', "UAE workflow installed: {$summary['stages']} stages and {$summary['transitions']} controlled transitions.");
    }
}
