<?php

namespace App\Http\Controllers\Inquiry;

use App\Http\Controllers\ApiController;
use App\Http\Requests\Inquiry\SubmitQuestionnaireRequest;
use App\Models\QuestionnaireAnswer;
use App\Models\Person;
use App\Models\Inquiry;
use App\Enums\QuestionnaireStep;
use App\Services\QuestionnaireService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Throwable;

/**
 * @OA\Post(
 *   path="/api/inquiry/questionnaire",
 *   tags={"Questionnaire"},
 *   summary="Submit questionnaire answers for a person",
 *   operationId="submit_questionnaire",
 *   security={{"auth":{}}},
 *
 *   @OA\Parameter(name="Accept-Language", in="header", description="Accept-Language", required=true, example="en", @OA\Schema(type="string")),
 *   @OA\Parameter(name="API-Key", in="header", description="API-Key", required=true, example="", @OA\Schema(type="string")),
 *   
 *   @OA\RequestBody(
 *     required=true,
 *     @OA\MediaType(
 *       mediaType="application/x-www-form-urlencoded",
 *       @OA\Schema(
 *         required={"questionnaire_id", "step", "answers"},
 *         @OA\Property(property="questionnaire_id", type="string", description="Questionnaire ID", example="01JMFX2XYZABCDEFGHIJKLMNOP"),
 *         @OA\Property(property="step", type="integer", description="Step number (1-4)", example=1),
 *         @OA\Property(property="answers", type="string", description="Answers as JSON string", example="{\"heart_surgery_10y\":\"no\",\"multiple_conditions\":\"no\"}"),
 *         @OA\Property(property="is_final_submission", type="boolean", description="Mark as final submission", example=false),
 *         @OA\Property(property="save_draft", type="boolean", description="Save as draft without evaluation", example=false)
 *       )
 *     )
 *   ),
 *   
 *   @OA\Response(
 *     response=200,
 *     description="Success",
 *     @OA\JsonContent(
 *       type="object",
 *       @OA\Property(property="result", type="object",
 *         @OA\Property(property="questionnaire", type="object",
 *           @OA\Property(property="questionnaire_id", type="string", example="01JMFX2XYZABCDEFGHIJKLMNOP"),
 *           @OA\Property(property="person_id", type="string", example="01JMFX2XYZABCDEFGHIJKLMNOP"),
 *           @OA\Property(property="person_name", type="string", example="John Doe"),
 *           @OA\Property(property="step_completed", type="integer", example=1),
 *           @OA\Property(property="next_step", type="integer", example=2),
 *           @OA\Property(property="completion_percentage", type="integer", example=25),
 *           @OA\Property(property="status", type="string", example="in_progress"),
 *           @OA\Property(property="is_eligible", type="boolean", example=true),
 *           @OA\Property(property="rate_category", type="string", example=null),
 *           @OA\Property(property="has_smoking_surcharge", type="boolean", example=false),
 *           @OA\Property(property="warnings", type="array",
 *             @OA\Items(type="string", example="Any 'Yes' answer in Step 1 will make you ineligible for insurance.")
 *           ),
 *           @OA\Property(property="next_actions", type="array",
 *             @OA\Items(type="string", example="Please proceed to Step 2: Rate Category C Trigger")
 *           )
 *         ),
 *         @OA\Property(property="summary", type="object",
 *           @OA\Property(property="step_evaluation", type="object",
 *             @OA\Property(property="step_passed", type="boolean", example=true),
 *             @OA\Property(property="messages", type="array",
 *               @OA\Items(type="string", example="Eligibility check passed")
 *             ),
 *             @OA\Property(property="triggers", type="array",
 *               @OA\Items(type="object",
 *                 @OA\Property(property="type", type="string", example="c_rate_trigger"),
 *                 @OA\Property(property="activated", type="boolean", example=false),
 *                 @OA\Property(property="message", type="string", example="No C rate triggers found")
 *               )
 *             )
 *           ),
 *           @OA\Property(property="premium_impact", type="object",
 *             @OA\Property(property="rate_category", type="string", example="A"),
 *             @OA\Property(property="premium_multiplier", type="number", format="float", example=1.0),
 *             @OA\Property(property="surcharge_percentage", type="number", format="float", example=0.0),
 *             @OA\Property(property="estimated_premium_increase", type="string", example="0%")
 *           )
 *         )
 *       )
 *     )
 *   ),
 *   @OA\Response(response=400, description="Bad Request"),
 *   @OA\Response(response=404, description="Not Found"),
 *   @OA\Response(response=422, description="Validation Error")
 * )
 */
class SubmitQuestionnaireController extends ApiController
{
    /**
     * @var QuestionnaireService
     */
    private $questionnaireService;

    /**
     * Constructor
     */
    public function __construct(QuestionnaireService $questionnaireService)
    {
        $this->questionnaireService = $questionnaireService;
    }

    /**
     * Handle the incoming request.
     */
    public function __invoke(SubmitQuestionnaireRequest $request): JsonResponse
    {
        try {
            DB::beginTransaction();
            
            $validated = $request->validated();
            
            // Find the questionnaire
            $questionnaire = QuestionnaireAnswer::find($validated['questionnaire_id']);
            if (!$questionnaire) {
                return $this->error('Questionnaire not found', [], 404);
            }
            
            // Load related data
            $questionnaire->load(['person', 'inquiry']);
            
            // Check if questionnaire is already completed
            if ($questionnaire->isCompleted()) {
                return $this->error('Questionnaire is already completed', [], 400);
            }
            
            // Get the step
            $step = QuestionnaireStep::from($validated['step']);
            
            // Process the answers based on step
            $processMethod = 'processStep' . $step->value;
            if (method_exists($this, $processMethod)) {
                $result = $this->$processMethod($questionnaire, $validated);
            } else {
                throw new \Exception("Invalid step: {$step->value}");
            }
            
            // If this is a draft save, don't evaluate
            $saveDraft = $validated['save_draft'] ?? false;
            if (!$saveDraft) {
                // Update questionnaire status
                $this->updateQuestionnaireStatus($questionnaire, $step, $validated);
                
                // If this is final submission or all steps are done, evaluate
                $isFinalSubmission = $validated['is_final_submission'] ?? false;
                if ($isFinalSubmission || $this->allStepsCompleted($questionnaire)) {
                    $this->finalizeQuestionnaire($questionnaire);
                }
            }
            
            // Update person's questionnaire status
            $this->updatePersonStatus($questionnaire->person, $questionnaire);
            
            // Prepare response
            $response = $this->prepareResponse($questionnaire, $result, $step);
            
            DB::commit();
            
            return $this->success($response);
            
        } catch (Throwable $e) {
            DB::rollBack();
            return $this->error($e->getMessage(), [], $e->getCode() ?: 500);
        }
    }

    /**
     * Process Step 1 (Eligibility Check) answers.
     */
    private function processStep1(QuestionnaireAnswer $questionnaire, array $validated): array
    {
        $answers = $validated['answers'];
        
        // Validate that all required questions are answered
        $step1Questions = $this->questionnaireService->getQuestionsForStep(QuestionnaireStep::ELIGIBILITY);
        $this->validateAllQuestionsAnswered($step1Questions, $answers, 'Step 1');
        
        // Check for any "yes" answers that would make person ineligible
        $hasIneligibleAnswer = $this->hasIneligibleAnswer($answers);
        
        $result = [
            'step_passed' => !$hasIneligibleAnswer,
            'answers_saved' => true,
            'evaluation' => [
                'has_ineligible_answer' => $hasIneligibleAnswer,
                'is_eligible' => !$hasIneligibleAnswer,
                'messages' => $hasIneligibleAnswer 
                    ? ['Eligibility check failed. Person is not eligible for insurance.'] 
                    : ['Eligibility check passed.'],
            ],
        ];
        
        // Save answers
        $questionnaire->step1_answers = $answers;
        $questionnaire->step1_passed = !$hasIneligibleAnswer;
        
        if ($hasIneligibleAnswer) {
            $questionnaire->step1_rejection_reason = 'Failed eligibility check in Step 1';
            $questionnaire->status = 'rejected';
            $questionnaire->rejection_reason = 'Not eligible based on medical questionnaire';
        }
        
        $questionnaire->save();
        
        return $result;
    }

    /**
     * Process Step 2 (C Rate Triggers) answers.
     */
    private function processStep2(QuestionnaireAnswer $questionnaire, array $validated): array
    {
        // First ensure Step 1 is passed
        if (!$questionnaire->step1_passed) {
            throw new \Exception('Must complete Step 1 first', 400);
        }
        
        $answers = $validated['answers'];
        
        // Validate that all required questions are answered
        $step2Questions = $this->questionnaireService->getQuestionsForStep(QuestionnaireStep::RATE_C_TRIGGER);
        $this->validateAllQuestionsAnswered($step2Questions, $answers, 'Step 2');
        
        // Check for any "yes" answers that would trigger C rate
        $hasRateCTrigger = $this->hasRateCTrigger($answers);
        
        $result = [
            'step_passed' => true, // Step 2 doesn't fail, just triggers C rate
            'answers_saved' => true,
            'triggers_c_rate' => $hasRateCTrigger,
            'evaluation' => [
                'has_c_rate_trigger' => $hasRateCTrigger,
                'messages' => $hasRateCTrigger 
                    ? ['C rate trigger activated. Person will be assigned Rate Category C.'] 
                    : ['No C rate triggers found.'],
            ],
        ];
        
        // Save answers
        $questionnaire->step2_answers = $answers;
        $questionnaire->step2_triggered_c_rate = $hasRateCTrigger;
        
        // If C rate is triggered, skip to Step 4 (smoking)
        if ($hasRateCTrigger) {
            $questionnaire->rate_category = 'C';
            $result['skip_to_step'] = 4;
        }
        
        $questionnaire->save();
        
        return $result;
    }

    /**
     * Process Step 3 (B Rate Triggers) answers.
     */
    private function processStep3(QuestionnaireAnswer $questionnaire, array $validated): array
    {
        // First ensure Step 2 is completed and C rate not triggered
        if (!$questionnaire->step2_answers) {
            throw new \Exception('Must complete Step 2 first', 400);
        }
        
        if ($questionnaire->step2_triggered_c_rate) {
            throw new \Exception('C rate already triggered, skipping Step 3', 400);
        }
        
        $answers = $validated['answers'];
        
        // Validate that all required questions are answered
        $step3Questions = $this->questionnaireService->getQuestionsForStep(QuestionnaireStep::RATE_B_TRIGGER);
        $this->validateAllQuestionsAnswered($step3Questions, $answers, 'Step 3');
        
        // Check for any "yes" answers that would trigger B rate
        $hasRateBTrigger = $this->hasRateBTrigger($answers);
        
        $result = [
            'step_passed' => true,
            'answers_saved' => true,
            'triggers_b_rate' => $hasRateBTrigger,
            'evaluation' => [
                'has_b_rate_trigger' => $hasRateBTrigger,
                'messages' => $hasRateBTrigger 
                    ? ['B rate trigger activated. Person will be assigned Rate Category B.'] 
                    : ['No B rate triggers found. Person will be assigned Rate Category A.'],
            ],
        ];
        
        // Save answers
        $questionnaire->step3_answers = $answers;
        $questionnaire->step3_triggered_b_rate = $hasRateBTrigger;
        
        // Determine rate category
        if ($hasRateBTrigger) {
            $questionnaire->rate_category = 'B';
        } else {
            $questionnaire->rate_category = 'A';
        }
        
        $questionnaire->save();
        
        return $result;
    }

    /**
     * Process Step 4 (Smoking) answers.
     */
    private function processStep4(QuestionnaireAnswer $questionnaire, array $validated): array
    {
        // First ensure previous steps are completed
        if (!$questionnaire->step1_answers || !$questionnaire->step1_passed) {
            throw new \Exception('Must complete Step 1 first', 400);
        }
        
        $answers = $validated['answers'];
        
        // Validate that all required questions are answered
        $step4Questions = $this->questionnaireService->getQuestionsForStep(QuestionnaireStep::SMOKING);
        $this->validateAllQuestionsAnswered($step4Questions, $answers, 'Step 4');
        
        // Extract smoking information
        $isSmoker = $answers['smoking_2y'] ?? false;
        $yearsSmoking = $answers['years_smoking'] ?? 0;
        $usesVaping = $answers['uses_vaping'] ?? false;
        
        $result = [
            'step_passed' => true,
            'answers_saved' => true,
            'smoking_info' => [
                'is_smoker' => $isSmoker,
                'years_smoking' => $yearsSmoking,
                'uses_vaping' => $usesVaping,
            ],
            'evaluation' => [
                'has_smoking_surcharge' => $isSmoker || $usesVaping,
                'surcharge_percentage' => ($isSmoker || $usesVaping) ? 10 : 0,
                'messages' => ($isSmoker || $usesVaping) 
                    ? ['Smoking/vaping detected. 10% surcharge will be applied.'] 
                    : ['No smoking/vaping detected. No surcharge applied.'],
            ],
        ];
        
        // Save answers
        $questionnaire->step4_answers = $answers;
        $questionnaire->is_smoker = $isSmoker;
        $questionnaire->years_smoking = $yearsSmoking;
        $questionnaire->uses_vaping = $usesVaping;
        
        // Apply smoking adjustment to rate factor
        if ($isSmoker || $usesVaping) {
            $questionnaire->rate_adjustment_factor = 1.10;
        }
        
        $questionnaire->save();
        
        return $result;
    }

    /**
     * Validate that all questions are answered.
     */
    private function validateAllQuestionsAnswered(array $questions, array $answers, string $stepName): void
    {
        foreach ($questions as $question) {
            $questionId = $question['code'] ?? null;
            if ($questionId && !isset($answers[$questionId])) {
                throw new \Exception("Missing answer for question '{$questionId}' in {$stepName}", 422);
            }
        }
    }

    /**
     * Check for ineligible answers in Step 1.
     */
    private function hasIneligibleAnswer(array $answers): bool
    {
        foreach ($answers as $answer) {
            if ($answer === 'yes' || $answer === true) {
                return true;
            }
        }
        return false;
    }

    /**
     * Check for C rate triggers in Step 2.
     */
    private function hasRateCTrigger(array $answers): bool
    {
        foreach ($answers as $answer) {
            if ($answer === 'yes' || $answer === true) {
                return true;
            }
        }
        return false;
    }

    /**
     * Check for B rate triggers in Step 3.
     */
    private function hasRateBTrigger(array $answers): bool
    {
        foreach ($answers as $answer) {
            if ($answer === 'yes' || $answer === true) {
                return true;
            }
        }
        return false;
    }

    /**
     * Update questionnaire status after step completion.
     */
    private function updateQuestionnaireStatus(QuestionnaireAnswer $questionnaire, QuestionnaireStep $step, array $validated): void
    {
        // Update status to in_progress if not already
        if ($questionnaire->status === 'pending') {
            $questionnaire->status = 'in_progress';
        }
        
        // Mark as completed if all steps are done
        if ($this->allStepsCompleted($questionnaire)) {
            $questionnaire->status = 'completed';
            $questionnaire->completed_at = now();
        }
        
        $questionnaire->save();
    }

    /**
     * Check if all steps are completed.
     */
    private function allStepsCompleted(QuestionnaireAnswer $questionnaire): bool
    {
        return $questionnaire->step1_answers !== null &&
               $questionnaire->step2_answers !== null &&
               $questionnaire->step3_answers !== null &&
               $questionnaire->step4_answers !== null;
    }

    /**
     * Finalize questionnaire evaluation.
     */
    private function finalizeQuestionnaire(QuestionnaireAnswer $questionnaire): void
    {
        // Evaluate the questionnaire
        $questionnaire->evaluate();
        
        // Update completion time if not set
        if (!$questionnaire->completed_at) {
            $questionnaire->completed_at = now();
        }
        
        $questionnaire->status = 'completed';
        $questionnaire->save();
    }

    /**
     * Update person's questionnaire status.
     */
    private function updatePersonStatus(Person $person, QuestionnaireAnswer $questionnaire): void
    {
        $person->questionnaire_completed = $questionnaire->isCompleted();
        $person->questionnaire_data = $questionnaire->getAllAnswers();
        
        if ($questionnaire->isCompleted()) {
            $person->questionnaire_completed_at = now();
            
            // Update person's rate category and smoking status
            $person->rate_category = $questionnaire->rate_category;
            $person->has_smoking_surcharge = $questionnaire->is_smoker || $questionnaire->uses_vaping;
            $person->is_smoker = $questionnaire->is_smoker;
            
            // Mark as ineligible if questionnaire was rejected
            if ($questionnaire->isRejected()) {
                $person->is_eligible = false;
                $person->ineligibility_reason = $questionnaire->rejection_reason;
            }
        }
        
        $person->save();
    }

    /**
     * Prepare response data.
     */
    private function prepareResponse(QuestionnaireAnswer $questionnaire, array $processResult, QuestionnaireStep $completedStep): array
    {
        $person = $questionnaire->person;
        $inquiry = $questionnaire->inquiry;
        
        // Determine next step
        $nextStep = $this->determineNextStep($questionnaire, $completedStep, $processResult);
        
        // Calculate completion percentage
        $completionPercentage = $questionnaire->getCompletionPercentage();
        
        // Get warnings and next actions
        list($warnings, $nextActions) = $this->getWarningsAndActions($questionnaire, $completedStep, $processResult);
        
        // Premium impact summary
        $premiumImpact = $this->calculatePremiumImpact($questionnaire);
        
        return [
            'questionnaire' => [
                'questionnaire_id' => $questionnaire->id,
                'person_id' => $person->id,
                'person_name' => $person->getFullName(),
                'age' => $person->age,
                'step_completed' => $completedStep->value,
                'next_step' => $nextStep?->value,
                'completion_percentage' => $completionPercentage,
                'status' => $questionnaire->status,
                'status_label' => $questionnaire->getStatusFormatted(),
                'is_eligible' => $questionnaire->isEligible(),
                'rate_category' => $questionnaire->rate_category,
                'rate_category_label' => $questionnaire->getRateCategoryDescription(),
                'has_smoking_surcharge' => $questionnaire->is_smoker || $questionnaire->uses_vaping,
                'warnings' => $warnings,
                'next_actions' => $nextActions,
                'can_proceed_to_payment' => $questionnaire->isCompleted() && $questionnaire->isEligible(),
            ],
            'summary' => [
                'step_evaluation' => [
                    'step_passed' => $processResult['step_passed'] ?? true,
                    'messages' => $processResult['evaluation']['messages'] ?? [],
                    'triggers' => [
                        [
                            'type' => 'eligibility',
                            'activated' => !$questionnaire->isEligible(),
                            'message' => $questionnaire->isEligible() ? 'Eligible' : 'Not eligible',
                        ],
                        [
                            'type' => 'c_rate_trigger',
                            'activated' => $questionnaire->step2_triggered_c_rate ?? false,
                            'message' => $questionnaire->step2_triggered_c_rate ? 'C rate triggered' : 'No C rate trigger',
                        ],
                        [
                            'type' => 'b_rate_trigger',
                            'activated' => $questionnaire->step3_triggered_b_rate ?? false,
                            'message' => $questionnaire->step3_triggered_b_rate ? 'B rate triggered' : 'No B rate trigger',
                        ],
                        [
                            'type' => 'smoking_surcharge',
                            'activated' => $questionnaire->is_smoker || $questionnaire->uses_vaping,
                            'message' => ($questionnaire->is_smoker || $questionnaire->uses_vaping) ? '10% surcharge applies' : 'No smoking surcharge',
                        ],
                    ],
                ],
                'premium_impact' => $premiumImpact,
                'inquiry_status' => [
                    'reference_number' => $inquiry->reference_number,
                    'total_people' => $inquiry->number_of_people,
                    'people_completed_questionnaire' => $inquiry->people->where('questionnaire_completed', true)->count(),
                    'people_remaining' => $inquiry->people->where('questionnaire_completed', false)->count(),
                ],
            ],
        ];
    }

    /**
     * Determine next step after completing current step.
     */
    private function determineNextStep(QuestionnaireAnswer $questionnaire, QuestionnaireStep $completedStep, array $processResult): ?QuestionnaireStep
    {
        // If questionnaire is completed or rejected, no next step
        if ($questionnaire->isCompleted() || $questionnaire->isRejected()) {
            return null;
        }
        
        // If C rate was triggered in Step 2, skip to Step 4
        if ($completedStep === QuestionnaireStep::RATE_C_TRIGGER && ($processResult['triggers_c_rate'] ?? false)) {
            return QuestionnaireStep::SMOKING;
        }
        
        // Otherwise go to next logical step
        return $completedStep->nextStep();
    }

    /**
     * Get warnings and next actions.
     */
    private function getWarningsAndActions(QuestionnaireAnswer $questionnaire, QuestionnaireStep $completedStep, array $processResult): array
    {
        $warnings = [];
        $nextActions = [];
        
        // If not eligible, show rejection message
        if (!$questionnaire->isEligible()) {
            $warnings[] = 'Person is not eligible for insurance based on medical questionnaire.';
            $nextActions[] = 'Please contact customer service for alternative options.';
            return [$warnings, $nextActions];
        }
        
        // Step-specific warnings
        switch ($completedStep) {
            case QuestionnaireStep::ELIGIBILITY:
                if ($questionnaire->step1_passed) {
                    $nextActions[] = 'Please proceed to Step 2: Rate Category C Trigger';
                }
                break;
                
            case QuestionnaireStep::RATE_C_TRIGGER:
                if ($processResult['triggers_c_rate'] ?? false) {
                    $warnings[] = 'Rate Category C triggered. This will result in higher premiums.';
                    $nextActions[] = 'Skipping Step 3, proceed to Step 4: Smoking Information';
                } else {
                    $nextActions[] = 'Please proceed to Step 3: Rate Category B Trigger';
                }
                break;
                
            case QuestionnaireStep::RATE_B_TRIGGER:
                if ($processResult['triggers_b_rate'] ?? false) {
                    $warnings[] = 'Rate Category B triggered. This will result in moderately higher premiums.';
                } else {
                    $warnings[] = 'Rate Category A confirmed. This is the lowest premium category.';
                }
                $nextActions[] = 'Please proceed to Step 4: Smoking Information';
                break;
                
            case QuestionnaireStep::SMOKING:
                if ($processResult['smoking_info']['is_smoker'] ?? false) {
                    $warnings[] = 'Smoking detected. 10% premium surcharge will be applied.';
                }
                if ($questionnaire->isCompleted()) {
                    $nextActions[] = 'Questionnaire completed. You can now proceed to payment.';
                }
                break;
        }
        
        // General warnings
        if ($completedStep->value < 4 && !$questionnaire->isCompleted()) {
            $warnings[] = 'All answers must be accurate. Incorrect information may affect coverage.';
        }
        
        return [$warnings, $nextActions];
    }

    /**
     * Calculate premium impact based on questionnaire results.
     */
    private function calculatePremiumImpact(QuestionnaireAnswer $questionnaire): array
    {
        $rateCategory = $questionnaire->rate_category ?? 'A';
        $hasSmokingSurcharge = $questionnaire->is_smoker || $questionnaire->uses_vaping;
        
        // Premium multipliers based on rate category
        $premiumMultipliers = [
            'A' => 1.0,
            'B' => 1.5,
            'C' => 2.5,
        ];
        
        $baseMultiplier = $premiumMultipliers[$rateCategory] ?? 1.0;
        $surchargeMultiplier = $hasSmokingSurcharge ? 1.10 : 1.0;
        $totalMultiplier = $baseMultiplier * $surchargeMultiplier;
        
        // Calculate percentage increases
        $baseIncrease = (($baseMultiplier - 1) * 100) . '%';
        $surchargePercentage = $hasSmokingSurcharge ? '10%' : '0%';
        $totalIncrease = (($totalMultiplier - 1) * 100) . '%';
        
        return [
            'rate_category' => $rateCategory,
            'premium_multiplier' => round($totalMultiplier, 2),
            'surcharge_percentage' => $hasSmokingSurcharge ? 10 : 0,
            'estimated_premium_increase' => $totalIncrease,
            'breakdown' => [
                'rate_category_multiplier' => round($baseMultiplier, 2),
                'rate_category_increase' => $baseIncrease,
                'smoking_surcharge_multiplier' => $surchargeMultiplier,
                'smoking_surcharge_increase' => $surchargePercentage,
            ],
            'description' => $this->getPremiumImpactDescription($rateCategory, $hasSmokingSurcharge),
        ];
    }

    /**
     * Get description of premium impact.
     */
    private function getPremiumImpactDescription(string $rateCategory, bool $hasSmokingSurcharge): string
    {
        $descriptions = [];
        
        if ($rateCategory === 'B') {
            $descriptions[] = 'Medium risk category (50% higher than base rate)';
        } elseif ($rateCategory === 'C') {
            $descriptions[] = 'High risk category (150% higher than base rate)';
        } else {
            $descriptions[] = 'Standard risk category (base rate)';
        }
        
        if ($hasSmokingSurcharge) {
            $descriptions[] = '10% smoking surcharge applies';
        }
        
        return implode('. ', $descriptions);
    }

    /**
     * Bulk submit questionnaire for multiple people.
     */
    public function bulkSubmit(SubmitQuestionnaireRequest $request): JsonResponse
    {
        try {
            DB::beginTransaction();
            
            $validated = $request->validated();
            $results = [];
            
            // This would be extended to handle bulk submissions
            // For now, process single submission
            $response = $this->__invoke($request);
            $responseData = json_decode($response->getContent(), true);
            
            $results[] = $responseData['result'] ?? [];
            
            DB::commit();
            
            return $this->success([
                'results' => $results,
                'summary' => [
                    'total_submitted' => 1,
                    'successful' => 1,
                    'failed' => 0,
                ],
            ]);
            
        } catch (Throwable $e) {
            DB::rollBack();
            return $this->error($e->getMessage(), [], $e->getCode() ?: 500);
        }
    }
}