<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Controller;
use App\Models\Listing;
use App\Models\RecentlyViewedListing;
use Illuminate\Http\Request;

class RecentlyViewedController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();

        $recentlyViewed = RecentlyViewedListing::query()
            ->where('user_id', $user->id)
            ->with(['listing', 'listing.category', 'listing.coverImage'])
            ->orderByDesc('viewed_at')
            ->limit(15)
            ->get();

        return response()->json([
            'data' => $recentlyViewed
        ]);
    }

    public function store(Request $request, Listing $listing)
    {
        abort_unless($listing->status === 'published', 404, 'İlan bulunamadı');


        $recentlyViewed = RecentlyViewedListing::updateOrCreate(
            [
                'user_id' => $request->user()->id,
                'listing_id' => $listing->id
            ],
            [
                'viewed_at' => now(),
            ]
        );

        $this->removeOldRecords($request->user()->id);

        return response()->json([
            'id' => $recentlyViewed->id
        ], 201);
    }

    public function destroy(Request $request,Listing $listing)
    {
        RecentlyViewedListing::query()
        ->where('user_id',$request->user()->id)
        ->where('listing_id',$listing->id)
        ->delete();

        return response()->json([
            'message' => 'İlan geçmişten kaldırıldı'
        ]);
    }

    public function clear(Request $request)
    {
        RecentlyViewedListing::query()
        ->where('user_id',$request->user()->id)
        ->delete();

        return response()->json([
            'message' => 'Görüntüleme geçmişi silindi'
        ]);
    }


    public function removeOldRecords(int $userId): void
    {
        $oldRecords = RecentlyViewedListing::query()
        ->where('user_id',$userId)
        ->orderByDesc('viewed_at')
        ->skip(50)
        ->take(1000)
        ->pluck('id');


        if($oldRecords->isNotEmpty())
            {
                RecentlyViewedListing::query()
                ->whereIn('id',$oldRecords)
                ->delete();
            }
    }
}
