<?php

/**
 * 文件功能：开发日志前台控制器
 * 对应独立页面 /changelog，展示已发布的版本更新日志
 * 支持懒加载（IntersectionObserver + 游标分页）
 *
 * @author   ChatRoom Laravel
 *
 * @version  1.0.0
 */

namespace App\Http\Controllers;

use App\Models\DevChangelog;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ChangelogController extends Controller
{
    /** 每次加载的条数 */
    private const PAGE_SIZE = 10;

    /**
     * 更新日志列表页（SSR首屏）
     * 预加载最新 10 条已发布日志
     */
    public function index(): View
    {
        $changelogs = DevChangelog::published()
            ->limit(self::PAGE_SIZE)
            ->get();

        return view('changelog.index', compact('changelogs'));
    }

    /**
     * 懒加载更多日志（JSON API）
     * 游标分页：传入已加载的最后一条 ID，返回更旧的 10 条
     *
     * @param  Request  $request  含 after_id 参数
     */
    public function loadMoreChangelogs(Request $request): JsonResponse
    {
        $afterId = (int) $request->input('after_id', PHP_INT_MAX);

        $items = DevChangelog::published()
            ->after($afterId)
            ->limit(self::PAGE_SIZE)
            ->get();

        $data = $items->map(fn (DevChangelog $log) => [
            'id' => $log->id,
            'version' => $log->version,
            'title' => $log->title,
            'type_label' => $log->type_label,
            'type_color' => $log->type_color,
            'content_html' => $log->content_html,
            'summary' => $log->summary,
            'published_at' => $log->published_at?->format('Y-m-d'),
        ]);

        return response()->json([
            'items' => $data,
            'has_more' => $items->count() === self::PAGE_SIZE,
        ]);
    }
}
