<?php

namespace App\Http\Controllers;

use App\Models\ImportedJob;
use App\Models\JobInterest;
use App\Services\Analytics\EngagementLogger;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;

class SavedJobController extends Controller
{
    public function store(Request $request, ImportedJob $job, EngagementLogger $engagementLogger): JsonResponse|RedirectResponse
    {
        Gate::authorize('save', $job);

        $request->user()->savedJobs()->firstOrCreate([
            'imported_job_id' => $job->id,
        ]);
        $request->user()->recordJobInterest($job, JobInterest::SOURCE_SAVED);
        $engagementLogger->record(
            $request->user(),
            'job_saved',
            'Saved '.$job->title.'.',
            ['imported_job_id' => $job->id],
            $job,
        );

        if ($request->expectsJson()) {
            return response()->json([
                'message' => 'Job saved.',
                'saved' => true,
                'saved_count' => $request->user()->savedJobs()->count(),
            ]);
        }

        return back()->with('status', 'Job saved.');
    }

    public function destroy(Request $request, ImportedJob $job, EngagementLogger $engagementLogger): JsonResponse|RedirectResponse
    {
        Gate::authorize('save', $job);

        $request->user()
            ->savedJobs()
            ->where('imported_job_id', $job->id)
            ->delete();
        $engagementLogger->record(
            $request->user(),
            'job_unsaved',
            'Removed saved job '.$job->title.'.',
            ['imported_job_id' => $job->id],
            $job,
        );

        if ($request->expectsJson()) {
            return response()->json([
                'message' => 'Saved job removed.',
                'saved' => false,
                'saved_count' => $request->user()->savedJobs()->count(),
            ]);
        }

        return back()->with('status', 'Saved job removed.');
    }
}
