import Link from "next/link";
import { redirect } from "next/navigation";
import { getSession } from "@/lib/auth";
import { db } from "@/lib/db";

type Item = { id: number; content: string; username: string; kind?: string; at: string };
function PostList({ items, empty }: { items: Item[]; empty: string }) { return items.length ? <ul className="reading-list">{items.map((item) => <li key={`${item.kind}-${item.id}`}><Link href={`/posts/${item.id}`}>{item.content.slice(0, 120) || "（空白貼文）"}</Link><br /><span className="meta">@{item.username} · {item.kind === "later" ? "稍後閱讀" : item.kind === "saved" ? "收藏" : "最近閱讀"} · {new Date(item.at + "Z").toLocaleString("zh-TW")}</span></li>)}</ul> : <p className="muted">{empty}</p>; }
export default async function ReadingPage() {
  const user = await getSession(); if (!user) redirect("/login");
  const saved = db.prepare("SELECT p.id,p.content,u.username,b.kind,b.created_at AS at FROM bookmarks b JOIN posts p ON p.id=b.post_id JOIN users u ON u.id=p.author_id WHERE b.user_id=? AND p.hidden=0 ORDER BY b.created_at DESC").all(user.id) as Item[];
  const history = db.prepare("SELECT p.id,p.content,u.username,h.last_read_at AS at FROM reading_history h JOIN posts p ON p.id=h.post_id JOIN users u ON u.id=p.author_id WHERE h.user_id=? AND p.hidden=0 ORDER BY h.last_read_at DESC LIMIT 50").all(user.id) as Item[];
  return <><h1>閱讀清單</h1><section className="card"><h2>收藏與稍後閱讀</h2><PostList items={saved} empty="尚未收藏任何貼文。" /></section><section className="card"><h2>最近閱讀</h2><PostList items={history} empty="尚無閱讀紀錄。" /></section></>;
}
