<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Models\Artwork;
use App\Services\UserStatsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\View\View;
use App\Support\AvatarUrl;

class FavoriteController extends Controller
{
    public function index(Request $request): View
    {
        $user = $request->user();
        $perPage = 20;

        $favTable = 'artwork_favourites';
        $sort = $request->query('sort', 'newest');
        $order = $sort === 'oldest' ? 'asc' : 'desc';
        $orderColumn = 'created_at';

        $query = DB::table($favTable)->where('user_id', (int) $user->id);
        if ($orderColumn) {
            $query = $query->orderBy($orderColumn, $order);
        }

        // Collect artwork ids in the correct order using the favourites table
        $artworkIds = $query->pluck('artwork_id')->values()->all();

        $page = max(1, (int) $request->query('page', 1));
        $slice = array_slice($artworkIds, ($page - 1) * $perPage, $perPage);

        $artworks = collect();
        if ($slice !== []) {
            $arts = Artwork::query()
                ->whereIn('id', $slice)
                ->with(['user.profile', 'categories'])
                ->withCount(['favourites', 'comments'])
                ->get()
                ->keyBy('id');

            foreach ($slice as $id) {
                $a = $arts->get($id);
                if (! $a) continue;

                $primaryCategory = $a->categories->sortBy('sort_order')->first();
                $username = $a->user?->username ?? $a->user?->name ?? '';

                $artworks->push((object) [
                    'id' => $a->id,
                    'name' => $a->title,
                    'title' => $a->title,
                    'thumb' => $a->thumbUrl('md') ?? $a->thumbnail_url ?? null,
                    'thumb_url' => $a->thumbUrl('md') ?? $a->thumbnail_url ?? null,
                    'slug' => $a->slug,
                    'author' => $username,
                    'uname' => $username,
                    'username' => $a->user?->username ?? '',
                    'avatar_url' => AvatarUrl::forUser(
                        (int) ($a->user_id ?? 0),
                        $a->user?->profile?->avatar_hash ?? null,
                        64
                    ),
                    'content_type_name' => $primaryCategory?->contentType?->name ?? '',
                    'content_type_slug' => $primaryCategory?->contentType?->slug ?? '',
                    'category_name' => $primaryCategory->name ?? '',
                    'category_slug' => $primaryCategory->slug ?? '',
                    'width' => $a->width,
                    'height' => $a->height,
                    'likes' => (int) ($a->favourites_count ?? $a->likes ?? 0),
                    'comments_count' => (int) ($a->comments_count ?? 0),
                    'published_at' => $a->published_at,
                ]);
            }
        }

        $paginator = new LengthAwarePaginator($artworks->toArray(), count($artworkIds), $perPage, $page, ['path' => $request->url(), 'query' => $request->query()]);

        return view('dashboard.favorites', ['artworks' => $paginator, 'sort' => $sort]);
    }

    public function destroy()
    {
        $user = auth()->user();
        $artwork = request()->route('artwork') ?? request()->input('artwork');
        if (! $artwork) {
            $last = collect(request()->segments())->last();
            if (is_numeric($last)) {
                $artwork = (int) $last;
            }
        }
        $artworkId = is_object($artwork) ? (int) $artwork->id : (int) $artwork;
        Log::info('FavoriteController::destroy', ['user_id' => $user->id ?? null, 'artworkId' => $artworkId]);
        // Look up creator before deleting so we can decrement their counter
        $creatorId = (int) DB::table('artworks')->where('id', $artworkId)->value('user_id');

        DB::table('artwork_favourites')
            ->where('user_id', (int) $user->id)
            ->where('artwork_id', $artworkId)
            ->delete();

        if ($creatorId) {
            app(UserStatsService::class)->decrementFavoritesReceived($creatorId);
        }

        return redirect()->route('dashboard.favorites')->with('status', 'favourite-removed');
    }
}
