<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreProfileRequest;
use App\Services\Analytics\EngagementLogger;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class ProfileController extends Controller
{
    public function edit(Request $request): View
    {
        $user = $request->user()->load(['profile', 'questionnaireResponse', 'resumeReport']);

        return view('profile.edit', [
            'user' => $user,
            'profile' => $user->profile,
            'questionnaire' => $user->questionnaireResponse,
            'resumeReport' => $user->resumeReport,
        ]);
    }

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

        DB::transaction(function () use ($user, $validated): void {
            $userUpdates = [
                'username' => filled($validated['username'] ?? null)
                    ? Str::lower((string) $validated['username'])
                    : null,
                'profile_completed_at' => now(),
            ];

            if (filled($validated['new_password'] ?? null)) {
                $userUpdates['password'] = Hash::make((string) $validated['new_password']);
                $userUpdates['password_set_at'] = now();
            }

            $user->profile()->updateOrCreate(
                ['user_id' => $user->id],
                [
                    'headline' => $validated['headline'],
                    'summary' => $validated['summary'] ?? null,
                    'current_role' => $validated['current_role'] ?? null,
                    'experience_level' => $validated['experience_level'],
                    'country_code' => isset($validated['country_code'])
                        ? strtoupper($validated['country_code'])
                        : null,
                    'city' => $validated['city'] ?? null,
                    'timezone' => $validated['timezone'] ?? null,
                    'skills' => $validated['skills'],
                    'preferred_roles' => $validated['preferred_roles'],
                    'preferred_categories' => $validated['preferred_categories'],
                    'links' => array_values(array_filter($validated['links'] ?? [])),
                    'availability' => $validated['availability'],
                    '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($userUpdates)->save();
        });

        $engagementLogger->record(
            $user,
            'profile_updated',
            'Updated applicant profile.',
            ['preferred_categories' => $validated['preferred_categories'] ?? []],
            $user->profile,
        );

        return redirect()->route('applicant.dashboard');
    }
}
