import { TradingSystemsView } from "@/components/trading-systems-view";
import { auth } from "@/auth";
import { headers } from "next/headers";
import { tradingSystems } from "@/lib/journal/trading-systems";
import { countTradingSystems } from "@/lib/journal/count-trading-systems";

export const dynamic = "force-dynamic";

export default async function Page({
  params,
  searchParams,
}: {
  params: Promise<{ slug: string }>
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
  const session = await auth.api.getSession({
    headers: await headers(),
  });

  const {
    q, // query
    c, // cursor
    o, // orderBy
    s, // order, expected to be one of 'asc' | 'desc'.
    // l, // limit
  } = await searchParams;

  const cleanCursor = c?.length && typeof c === 'string' ? c : undefined;
  const cleanOrderBy = o?.length && typeof o === 'string' ? o : undefined;
  const cleanOrder = s?.length && typeof s === 'string' ? (s.toLowerCase() === 'asc' ? 'asc' : 'desc') : undefined;
  const cleanQuery = q?.length && typeof q === 'string' ? q : undefined;

  const count = await countTradingSystems({
    userId: session?.user.id,
    query: cleanQuery
  });

  const systems = session?.user.id ? await tradingSystems({
    userId: session.user.id,
    paging: {
      cursor: cleanCursor,
      orderBy: cleanOrderBy,
      order: cleanOrder,
    },
  }) : [];

  return <TradingSystemsView initialSystems={systems} count={count} />
}
