<?php

namespace App\Http\Controllers\Api;

use App\Models\Hentai;
use App\Models\PopularMonthly;

use Illuminate\Support\Facades\Cache;
use App\Http\Controllers\Controller;

class HentaiApiController extends Controller
{
    /**
     * Get a list of all hentai with it's episodes
     */
    public function index()
    {
        // Cache for 10 minutes
        $data = Cache::remember('api_hentai_list', now()->addMinutes(10), function () {
            return Hentai::with('episodes')
                ->orderBy('created_at', 'desc')
                ->get()
                ->map(function ($hentai) {
                    return [
                        'title'     => $hentai->episodes[0]->title,
                        'title_jpn' => $hentai->episodes[0]->title_jpn,
                        'slug'      => $hentai->slug,
                        'episodes'  => $hentai->episodes->map(function ($ep) {
                            return [
                                'episode'   => $ep->episode,
                                'slug'      => $ep->slug,
                            ];
                        }),
                    ];
                });
        });

        return response()->json($data);
    }

    /**
     * Get monthly views by day for stats
     */
    public function getMonthlyViews()
    {
        // Cache for 60 minutes
        $data = Cache::remember('api_hentai_list', now()->addMinutes(60), function () {
            return PopularMonthly::selectRaw('DATE(created_at) as date, COUNT(*) as count')
                ->groupBy('date')
                ->orderBy('date', 'asc')
                ->get();
        });

        return response()->json($data);
    }
}
