import { AccountsView } from "@/components/accounts-view"
import { auth } from "@/auth"
import { headers } from "next/headers"
import { tradingAccounts } from "@/lib/journal/trading-accounts";
import { countTradingAccounts } from "@/lib/journal/count-trading-accounts";
import { brokers } from "@/lib/journal/brokers";
import { currencies } from "@/lib/journal/currencies"

import type { TradingAccountType } from "@/generated/prisma/client";

export const dynamic = "force-dynamic";

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

  const count = await countTradingAccounts({userId: session?.user.id});

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

  const cleanBroker = broker?.length && typeof broker === 'string' ? broker : undefined;
  const cleanCurrency = currency?.length && typeof currency === 'string' ? currency : undefined;
  const cleanType:TradingAccountType | undefined = type?.length && (typeof type === 'string')
  && (['LIVE', 'DEMO']).includes(type.toUpperCase())
    ? type.toUpperCase() as TradingAccountType : undefined;
  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 accounts = session?.user.id ? await tradingAccounts({
    userId: session.user.id,
    broker: cleanBroker,
    type: cleanType,
    currency: cleanCurrency,
    query: cleanQuery,
    paging: {
      cursor: cleanCursor,
      orderBy: cleanOrderBy,
      order: cleanOrder,
    },
  }) : [];

  const paged = accounts.slice(0, Math.max(20, accounts.length));

  const allBrokers = await brokers({ userId: session?.user.id ?? '' });
  const allCurrencies = await currencies({ userId: session?.user.id ?? '' });

  return <AccountsView
    accounts={paged}
    cursor={paged.length ? paged[paged.length - 1].id : undefined}
    count={count}
    queryCount={accounts.length}
    query={cleanQuery}
    filter={{
      broker: cleanBroker,
      type: cleanType,
      currency: cleanCurrency,
    }}
    order={cleanOrder}
    orderBy={cleanOrderBy}
    types={['LIVE', 'DEMO']}
    currencies={allCurrencies}
    brokers={allBrokers}
  />
}
