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

export default async function NotificationsPage() {
  const user = await getSession(); if (!user) redirect("/login");
  const notifications = db.prepare("SELECT n.*,u.username AS actor_username FROM notifications n LEFT JOIN users u ON u.id=n.actor_id WHERE n.user_id=? ORDER BY n.created_at DESC LIMIT 100").all(user.id) as any[];
  return <><div className="space"><h1>通知</h1><form action="/api/notifications/read" method="post"><button>全部標示已讀</button></form></div>{notifications.length ? <ul className="reading-list">{notifications.map((item) => <li className={item.read_at ? "" : "unread"} key={item.id}><Link href={`/posts/${item.post_id}`}>{item.message}</Link><br /><span className="meta">{new Date(item.created_at + "Z").toLocaleString("zh-TW")}</span>{!item.read_at && <form action="/api/notifications/read" method="post"><input type="hidden" name="id" value={item.id} /><button>標示已讀</button></form>}</li>)}</ul> : <p className="muted">沒有通知。</p>}</>;
}
