<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\Artwork;
use App\Services\ArtworkService;
use App\Services\Maturity\ArtworkMaturityService;
use Illuminate\Http\Request;

class DailyUploadsController extends Controller
{
    protected ArtworkService $artworks;

    public function __construct(ArtworkService $artworks, private readonly ArtworkMaturityService $maturity)
    {
        $this->artworks = $artworks;
    }

    public function index(Request $request)
    {
        $isAjax = $request->boolean('ajax');
        $datum = $request->query('datum');

        if ($isAjax && $datum) {
            $arts = $this->fetchByDate($datum);
            return view('web.partials.daily-uploads-grid', ['arts' => $arts])->render();
        }

        $dates = [];
        for ($x = 0; $x > -15; $x--) {
            $ts = strtotime(sprintf('%+d days', $x));
            $dates[] = [
                'iso' => date('Y-m-d', $ts),
                'label' => date('d. F Y', $ts),
            ];
        }

        $recent = $this->fetchRecent();

        return view('web.daily-uploads', [
            'dates' => $dates,
            'recent' => $recent,
            'page_title' => 'Daily Uploads',
        ]);
    }

    private function fetchByDate(string $date)
    {
        $ars = Artwork::public()
            ->published()
            ->whereDate('published_at', $date)
            ->orderByDesc('published_at')
            ->with(['user:id,name', 'categories' => function ($q) {
                $q->select('categories.id', 'categories.name', 'categories.sort_order');
            }])
            ->get();

        return $this->prepareArts($ars);
    }

    private function fetchRecent()
    {
        $start = now()->subDays(7)->startOfDay();

        $ars = Artwork::public()
            ->published()
            ->where('published_at', '>=', $start)
            ->orderByDesc('published_at')
            ->with(['user:id,name', 'categories' => function ($q) {
                $q->select('categories.id', 'categories.name', 'categories.sort_order');
            }])
            ->get();

        return $this->prepareArts($ars);
    }

    private function prepareArts($ars)
    {
        $items = $ars->map(function (Artwork $ar): array {
            $primaryCategory = $ar->categories->sortBy('sort_order')->first();
            $present = \App\Services\ThumbnailPresenter::present($ar, 'md');

            return $this->maturity->decoratePayload([
                'id' => $ar->id,
                'name' => $ar->title,
                'thumb' => $present['url'],
                'thumb_srcset' => $present['srcset'] ?? $present['url'],
                'gid_num' => $primaryCategory ? ((int) $primaryCategory->id % 5) * 5 : 0,
                'category_name' => $primaryCategory->name ?? '',
                'uname' => $ar->user->name ?? 'Skinbase',
            ], $ar, request()->user());
        })->values()->all();

        return collect($this->maturity->filterPayloadItems($items, request()->user()))
            ->map(static fn (array $item): object => (object) $item)
            ->values();
    }
}
