<?php

namespace App\Http\Controllers;

use App\Models\JobAlertPreference;
use App\Models\ImportedJob;
use App\Services\Analytics\EngagementLogger;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class JobAlertPreferenceController extends Controller
{
    public function edit(Request $request): View
    {
        $preference = $request->user()->jobAlertPreference()->firstOrCreate([], [
            'enabled' => true,
            'frequency' => 'daily',
            'minimum_match_score' => 45,
        ]);

        return view('job-alerts.preferences', [
            'preference' => $preference,
            'categoryOptions' => ImportedJob::query()
                ->active()
                ->whereNotNull('category')
                ->distinct()
                ->orderBy('category')
                ->pluck('category')
                ->filter()
                ->values()
                ->all(),
        ]);
    }

    public function update(Request $request, EngagementLogger $engagementLogger): RedirectResponse
    {
        $validated = $request->validate([
            'enabled' => ['nullable', 'boolean'],
            'frequency' => ['required', 'string', 'in:daily,weekly'],
            'minimum_match_score' => ['required', 'integer', 'min:0', 'max:100'],
            'categories' => ['nullable', 'array'],
            'categories.*' => ['string', 'max:80'],
            'keywords' => ['nullable', 'string', 'max:1000'],
        ]);

        $enabled = (bool) ($validated['enabled'] ?? false);

        $preference = $request->user()->jobAlertPreference()->updateOrCreate([], [
            'enabled' => $enabled,
            'frequency' => $validated['frequency'],
            'minimum_match_score' => $validated['minimum_match_score'],
            'categories' => array_values(array_filter($validated['categories'] ?? [])),
            'keywords' => collect(preg_split('/[\n,]+/', (string) ($validated['keywords'] ?? '')) ?: [])
                ->map(fn (string $keyword): string => trim($keyword))
                ->filter()
                ->values()
                ->all(),
            'unsubscribed_at' => $enabled ? null : now(),
        ]);

        $engagementLogger->record(
            $request->user(),
            'job_alert_preferences_updated',
            'Updated matched-job email preferences.',
            [
                'enabled' => $enabled,
                'frequency' => $validated['frequency'],
                'minimum_match_score' => $validated['minimum_match_score'],
            ],
            $preference,
        );

        return back()->with('status', 'Job alert preferences updated.');
    }

    public function unsubscribe(JobAlertPreference $preference, EngagementLogger $engagementLogger): View
    {
        $preference->forceFill([
            'enabled' => false,
            'unsubscribed_at' => now(),
        ])->save();

        $preference->user?->jobAlertEmailLogs()
            ->whereNull('unsubscribed_at')
            ->latest()
            ->limit(1)
            ->get()
            ->each(fn ($log): mixed => $log->markEvent('unsubscribed'));

        $engagementLogger->record(
            $preference->user,
            'job_alert_unsubscribed',
            'User unsubscribed from matched job alert emails.',
            ['job_alert_preference_id' => $preference->id],
            $preference,
        );

        return view('job-alerts.unsubscribed');
    }
}
