<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreQuestionnaireRequest;
use App\Services\Analytics\EngagementLogger;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\DB;

class QuestionnaireController extends Controller
{
    public function show(): View
    {
        return view('questionnaire.show');
    }

    public function store(StoreQuestionnaireRequest $request, EngagementLogger $engagementLogger): RedirectResponse
    {
        $user = $request->user();
        $validated = $request->validated();

        DB::transaction(function () use ($user, $validated): void {
            $user->questionnaireResponse()->updateOrCreate(
                ['user_id' => $user->id],
                [
                    'answers' => $validated['answers'],
                    'preferred_categories' => $validated['preferred_categories'],
                    'preferred_roles' => $validated['preferred_roles'],
                    'skills' => $validated['skills'],
                    'experience_level' => $validated['experience_level'],
                    'availability' => $validated['availability'],
                    'preferred_timezone' => $validated['preferred_timezone'] ?? null,
                    'country_code' => isset($validated['country_code'])
                        ? strtoupper($validated['country_code'])
                        : null,
                    'salary_currency' => strtoupper($validated['salary_currency']),
                    'salary_min' => $validated['salary_min'] ?? null,
                    'open_to_contract' => $validated['open_to_contract'],
                    'open_to_full_time' => $validated['open_to_full_time'],
                    'completed_at' => now(),
                ]
            );

            $user->forceFill([
                'questionnaire_completed_at' => now(),
            ])->save();
        });

        $engagementLogger->record(
            $user,
            'questionnaire_completed',
            'Completed the applicant questionnaire.',
            ['preferred_categories' => $validated['preferred_categories'] ?? []],
            $user->questionnaireResponse,
        );

        return redirect()->route('payment.checkout');
    }
}
