<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Artwork;
use App\Services\ArtworkSearchService;
use App\Services\ArtworkService;
use App\Services\EarlyGrowth\FeedBlender;
use App\Services\EarlyGrowth\GridFiller;
use App\Services\Recommendation\RecommendationService;
use App\Services\ThumbnailPresenter;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * DiscoverController
 *
 * Powers the /discover/* discovery pages:
 *   - /discover/trending       → most viewed in last 7 days
 *   - /discover/fresh          → latest uploads  (replaces /uploads/latest)
 *   - /discover/top-rated      → highest favourite count
 *   - /discover/most-downloaded → most downloaded all-time
 *   - /discover/on-this-day    → published on this calendar day in previous years
 *   - /discover/for-you        → personalised feed (auth required)
 */
final class DiscoverController extends Controller
{
    public function __construct(
        private readonly ArtworkService        $artworkService,
        private readonly ArtworkSearchService  $searchService,
        private readonly RecommendationService $recoService,
        private readonly FeedBlender           $feedBlender,
        private readonly GridFiller            $gridFiller,
    ) {}

    // ─── /discover/trending ──────────────────────────────────────────────────

    public function trending(Request $request)
    {
        $perPage = 24;
        $page    = max(1, (int) $request->query('page', 1));
        $results = $this->searchService->discoverTrending($perPage);
        $results = $this->gridFiller->fill($results, 0, $page);
        $this->hydrateDiscoverSearchResults($results);

        return view('web.discover.index', [
            'artworks'    => $results,
            'page_title'  => 'Trending Artworks',
            'section'     => 'trending',
            'description' => 'The most-viewed artworks on Skinbase over the past 7 days.',
            'icon'        => 'fa-fire',
        ]);
    }

    // ─── /discover/rising ────────────────────────────────────────────────────

    public function rising(Request $request)
    {
        $perPage = 24;
        $page    = max(1, (int) $request->query('page', 1));
        $results = $this->searchService->discoverRising($perPage);
        $results = $this->gridFiller->fill($results, 0, $page);
        $this->hydrateDiscoverSearchResults($results);

        return view('web.discover.index', [
            'artworks'    => $results,
            'page_title'  => 'Rising Now',
            'section'     => 'rising',
            'description' => 'Fastest growing artworks right now.',
            'icon'        => 'fa-rocket',
        ]);
    }

    // ─── /discover/fresh ─────────────────────────────────────────────────────

    public function fresh(Request $request)
    {
        $perPage = 24;
        $page    = max(1, (int) $request->query('page', 1));
        $results = $this->searchService->discoverFresh($perPage);
        // EGS: blend fresh feed with curated + spotlight on page 1
        $results = $this->feedBlender->blend($results, $perPage, $page);
        $results = $this->gridFiller->fill($results, 0, $page);
        $this->hydrateDiscoverSearchResults($results);

        return view('web.discover.index', [
            'artworks'    => $results,
            'page_title'  => 'Fresh Uploads',
            'section'     => 'fresh',
            'description' => 'The latest artworks just uploaded to Skinbase.',
            'icon'        => 'fa-bolt',
        ]);
    }

    // ─── /discover/top-rated ─────────────────────────────────────────────────

    public function topRated(Request $request)
    {
        $perPage = 24;
        $page    = max(1, (int) $request->query('page', 1));
        $results = $this->searchService->discoverTopRated($perPage);
        $results = $this->gridFiller->fill($results, 0, $page);
        $this->hydrateDiscoverSearchResults($results);

        return view('web.discover.index', [
            'artworks'    => $results,
            'page_title'  => 'Top Rated Artworks',
            'section'     => 'top-rated',
            'description' => 'The most-loved artworks on Skinbase, ranked by community favourites.',
            'icon'        => 'fa-medal',
        ]);
    }

    // ─── /discover/most-downloaded ───────────────────────────────────────────

    public function mostDownloaded(Request $request)
    {
        $perPage = 24;
        $page    = max(1, (int) $request->query('page', 1));
        $results = $this->searchService->discoverMostDownloaded($perPage);
        $results = $this->gridFiller->fill($results, 0, $page);
        $this->hydrateDiscoverSearchResults($results);

        return view('web.discover.index', [
            'artworks'    => $results,
            'page_title'  => 'Most Downloaded',
            'section'     => 'most-downloaded',
            'description' => 'All-time most downloaded artworks on Skinbase.',
            'icon'        => 'fa-download',
        ]);
    }

    // ─── /discover/on-this-day ───────────────────────────────────────────────

    public function onThisDay(Request $request)
    {
        $perPage = 24;
        $today   = now();

        $artworks = Artwork::query()
            ->public()
            ->published()
            ->with([
                'user:id,name',
                'user.profile:user_id,avatar_hash',
                'categories:id,name,slug,content_type_id,parent_id,sort_order',
            ])
            ->whereRaw('MONTH(published_at) = ?', [$today->month])
            ->whereRaw('DAY(published_at) = ?',   [$today->day])
            ->whereRaw('YEAR(published_at) < ?',   [$today->year])
            ->orderByDesc('published_at')
            ->paginate($perPage)
            ->withQueryString();

        $artworks->getCollection()->transform(fn ($a) => $this->presentArtwork($a));

        return view('web.discover.index', [
            'artworks'    => $artworks,
            'page_title'  => 'On This Day',
            'section'     => 'on-this-day',
            'description' => 'Artworks published on ' . $today->format('F j') . ' in previous years.',
            'icon'        => 'fa-calendar-day',
        ]);
    }

    // ─── /creators/rising ────────────────────────────────────────────────────

    public function risingCreators(Request $request)
    {
        $perPage = 20;

        // Creators with artworks published in the last 90 days, ordered by total recent views.
        $hasStats = false;
        try { $hasStats = Schema::hasTable('artwork_stats'); } catch (\Throwable) {}

        if ($hasStats) {
            $sub = Artwork::query()
                ->public()
                ->published()
                ->join('artwork_stats', 'artwork_stats.artwork_id', '=', 'artworks.id')
                ->where('artworks.published_at', '>=', now()->subDays(90))
                ->selectRaw('artworks.user_id, SUM(artwork_stats.views) as recent_views, MAX(artworks.published_at) as latest_published')
                ->groupBy('artworks.user_id');
        } else {
            $sub = Artwork::query()
                ->public()
                ->published()
                ->where('published_at', '>=', now()->subDays(90))
                ->selectRaw('user_id, COUNT(*) as recent_views, MAX(published_at) as latest_published')
                ->groupBy('user_id');
        }

        $creators = DB::table(DB::raw('(' . $sub->toSql() . ') as t'))
            ->mergeBindings($sub->getQuery())
            ->join('users as u', 'u.id', '=', 't.user_id')
            ->leftJoin('user_profiles as up', 'up.user_id', '=', 't.user_id')
            ->select('u.id as user_id', 'u.name as uname', 'u.username', 't.recent_views', 't.latest_published', 'up.avatar_hash')
            ->orderByDesc('t.recent_views')
            ->orderByDesc('t.latest_published')
            ->paginate($perPage)
            ->withQueryString();

        $creators->getCollection()->transform(function ($row) {
            return (object) [
                'user_id'     => $row->user_id,
                'uname'       => $row->uname,
                'username'    => $row->username,
                'total'       => (int) $row->recent_views,
                'metric'      => 'views',
                'avatar_hash' => $row->avatar_hash ?? null,
            ];
        });

        return view('web.creators.rising', [
            'creators'   => $creators,
            'page_title' => 'Rising Creators — Skinbase',
        ]);
    }

    // ─── /discover/for-you ───────────────────────────────────────────────────

    /**
     * Personalised "For You" feed page.
     *
     * Uses RecommendationService (Phase 1 tag-affinity + creator-affinity pipeline)
     * and renders the standard discover grid view.  Guest users are redirected
     * to the trending page per spec.
     */
    public function forYou(Request $request)
    {
        $user    = $request->user();
        $limit   = 40;
        $cursor  = $request->query('cursor') ?: null;

        // Retrieve the paginated feed (service handles Meilisearch + reranking + cache)
        $feedResult = $this->recoService->forYouFeed(
            user:   $user,
            limit:  $limit,
            cursor: is_string($cursor) ? $cursor : null,
        );

        $artworkItems = $feedResult['data'] ?? [];

        // Build a simple presentable collection
        $artworks = collect($artworkItems)->map(function (array $item) {
            $width     = isset($item['width'])  && $item['width']  > 0 ? (int) $item['width']  : null;
            $height    = isset($item['height']) && $item['height'] > 0 ? (int) $item['height'] : null;
            $avatarUrl = \App\Support\AvatarUrl::forUser((int) ($item['author_id'] ?? 0), null, 64);

            return (object) [
                'id'            => $item['id']            ?? 0,
                'name'          => $item['title']         ?? 'Untitled',
                'category_name' => $item['category_name'] ?? '',
                'category_slug' => $item['category_slug'] ?? '',
                'thumb_url'     => $item['thumbnail_url'] ?? null,
                'thumb_srcset'  => $item['thumbnail_url'] ?? null,
                'uname'         => $item['author']        ?? 'Artist',
                'username'      => $item['username']      ?? '',
                'avatar_url'    => $avatarUrl,
                'published_at'  => $item['published_at']  ?? null,
                'slug'          => $item['slug']          ?? '',
                'width'         => $width,
                'height'        => $height,
            ];
        });

        $meta       = $feedResult['meta'] ?? [];
        $nextCursor = $meta['next_cursor'] ?? null;

        return view('web.discover.for-you', [
            'artworks'    => $artworks,
            'page_title'  => 'For You',
            'section'     => 'for-you',
            'description' => 'Artworks picked for you based on your taste.',
            'icon'        => 'fa-wand-magic-sparkles',
            'next_cursor' => $nextCursor,
            'cache_status' => $meta['cache_status'] ?? null,
        ]);
    }

    // ─── /discover/following ─────────────────────────────────────────────────

    public function following(Request $request)
    {
        $user    = $request->user();
        $perPage = 24;

        // Subquery: IDs of users this viewer follows
        $followingIds = DB::table('user_followers')
            ->where('follower_id', $user->id)
            ->pluck('user_id');

        if ($followingIds->isEmpty()) {
            // Trending fallback: show popular artworks so the page isn't blank
            try {
                $fallbackResults = $this->searchService->discoverTrending(12);
                $fallbackArtworks = $fallbackResults->getCollection()
                    ->transform(fn ($a) => $this->presentArtwork($a));
            } catch (\Throwable) {
                $fallbackArtworks = collect();
            }

            // Suggested creators: most-followed users the viewer doesn't follow yet
            $suggestedCreators = DB::table('users')
                ->join('user_statistics', 'users.id', '=', 'user_statistics.user_id')
                ->where('users.id', '!=', $user->id)
                ->whereNotNull('users.email_verified_at')
                ->where('users.is_active', true)
                ->orderByDesc('user_statistics.followers_count')
                ->limit(8)
                ->select(
                    'users.id',
                    'users.name',
                    'users.username',
                    'user_statistics.followers_count',
                )
                ->get();

            return view('web.discover.index', [
                'artworks'           => collect(),
                'page_title'         => 'Following Feed',
                'section'            => 'following',
                'description'        => 'Follow some creators to see their work here.',
                'icon'               => 'fa-user-group',
                'empty'              => true,
                'fallback_trending'  => $fallbackArtworks,
                'fallback_creators'  => $suggestedCreators,
            ]);
        }

        $page    = (int) request()->get('page', 1);
        $cacheKey = "discover.following.{$user->id}.p{$page}";

        $artworks = Cache::remember($cacheKey, 60, function () use ($user, $followingIds, $perPage): \Illuminate\Pagination\LengthAwarePaginator {
            return Artwork::query()
                ->public()
                ->published()
                ->with(['user:id,name,username', 'categories:id,name,slug,content_type_id,parent_id,sort_order'])
                ->whereIn('user_id', $followingIds)
                ->orderByDesc('published_at')
                ->paginate($perPage)
                ->withQueryString();
        });

        $artworks->getCollection()->transform(fn ($a) => $this->presentArtwork($a));

        return view('web.discover.index', [
            'artworks'    => $artworks,
            'page_title'  => 'Following Feed',
            'section'     => 'following',
            'description' => 'The latest artworks from creators you follow.',
            'icon'        => 'fa-user-group',
        ]);
    }

    // ─── Helpers ─────────────────────────────────────────────────────────────

    private function hydrateDiscoverSearchResults($paginator): void
    {
        if (!is_object($paginator) || !method_exists($paginator, 'getCollection') || !method_exists($paginator, 'setCollection')) {
            return;
        }

        $items = $paginator->getCollection();
        if (!$items || $items->isEmpty()) {
            return;
        }

        $ids = $items
            ->pluck('id')
            ->filter(fn ($id) => is_numeric($id) && (int) $id > 0)
            ->map(fn ($id) => (int) $id)
            ->values();

        if ($ids->isEmpty()) {
            return;
        }

        $byId = Artwork::query()
            ->whereIn('id', $ids)
            ->with([
                'user:id,name,username',
                'user.profile:user_id,avatar_hash',
                'categories:id,name,slug,content_type_id,parent_id,sort_order',
            ])
            ->get()
            ->keyBy('id');

        $paginator->setCollection(
            $items->map(function ($item) use ($byId) {
                $id = (int) ($item->id ?? 0);
                $full = $id > 0 ? $byId->get($id) : null;

                if ($full instanceof Artwork) {
                    return $this->presentArtwork($full);
                }

                return (object) [
                    'id'            => $item->id ?? 0,
                    'name'          => $item->title ?? $item->name ?? 'Untitled',
                    'category_name' => $item->category_name ?? $item->category ?? '',
                    'category_slug' => $item->category_slug ?? '',
                    'thumb_url'     => $item->thumbnail_url ?? $item->thumb_url ?? $item->thumb ?? null,
                    'thumb_srcset'  => $item->thumb_srcset ?? null,
                    'uname'         => $item->author ?? $item->uname ?? 'Skinbase',
                    'username'      => $item->username ?? '',
                    'avatar_url'    => \App\Support\AvatarUrl::forUser((int) ($item->user_id ?? $item->author_id ?? 0), null, 64),
                    'published_at'  => $item->published_at ?? null,
                    'width'         => isset($item->width)  && $item->width  ? (int) $item->width  : null,
                    'height'        => isset($item->height) && $item->height ? (int) $item->height : null,
                ];
            })
        );
    }

    private function presentArtwork(Artwork $artwork): object
    {
        $primaryCategory = $artwork->categories->sortBy('sort_order')->first();
        $present         = ThumbnailPresenter::present($artwork, 'md');
        $avatarUrl       = \App\Support\AvatarUrl::forUser(
            (int) ($artwork->user_id ?? 0),
            $artwork->user?->profile?->avatar_hash ?? null,
            64
        );

        return (object) [
            'id'            => $artwork->id,
            'name'          => $artwork->title,
            'content_type_name' => $primaryCategory?->contentType?->name ?? '',
            'content_type_slug' => $primaryCategory?->contentType?->slug ?? '',
            'category_name' => $primaryCategory->name ?? '',
            'category_slug' => $primaryCategory->slug ?? '',
            'gid_num'       => $primaryCategory ? ((int) $primaryCategory->id % 5) * 5 : 0,
            'thumb_url'     => $present['url'],
            'thumb_srcset'  => $present['srcset'] ?? $present['url'],
            'uname'         => $artwork->user->name ?? 'Skinbase',
            'avatar_url'    => $avatarUrl,
            'published_at'  => $artwork->published_at,
            'width'         => $artwork->width  ?? null,
            'height'        => $artwork->height ?? null,
        ];
    }
}
