<?php

namespace App\Http\Controllers;

use App\Models\Lead;
use App\Models\ToolResult;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ToolResultController extends Controller
{
    public function store(Request $request, string $tool): JsonResponse
    {
        abort_unless(in_array($tool, ['budget', 'debt-payoff', 'compound-growth', 'emergency-fund', 'values-clarification', 'wealth-goals', 'loan-cost', 'retirement']), 404);

        $data = $request->validate([
            'label' => ['nullable', 'string', 'max:120'],
            'inputs' => ['required', 'array'],
            'outputs' => ['nullable', 'array'],
            'email' => [\Illuminate\Validation\Rule::requiredIf(! $request->user()), 'nullable', 'email', 'max:190'],
            'name' => ['nullable', 'string', 'max:120'],
        ]);

        $result = ToolResult::create([
            'user_id' => $request->user()?->id,
            'tool' => $tool,
            'label' => $data['label'] ?? null,
            'inputs' => $data['inputs'],
            'outputs' => $data['outputs'] ?? null,
        ]);

        if (! $request->user() && ! empty($data['email'])) {
            Lead::firstOrCreate(
                ['email' => $data['email'], 'source' => "tool:{$tool}"],
                ['name' => $data['name'] ?? null, 'meta' => ['tool_result_id' => $result->id]]
            );
        }

        return response()->json(['saved' => true, 'id' => $result->id]);
    }
}
