import { Wallet } from "@/types/auth";
import { INITIAL_WALLET } from "./const/wallet.const";
import { PaginatedData, Pagination } from "@/types/common.type";
import { Transaction } from "./types/transaction.type";
import { getTransactionsV1 } from "@/services/v1/transactionAdapter";
import { WalletBalanceSection } from "./sections/balance";

import { WalletHistorySection } from "./sections/history";
import { redirect } from "next/navigation";
import { getServerAuthData } from "@/lib/server-auth";
import { extractCurrentUserV1, getCurrentUserV1 } from "@/services/v1/authAdapter";

export const WalletModule = async () => {
  let wallet: Wallet = INITIAL_WALLET;
  let user = null;

  // Get auth data with automatic refresh handling
  // This will handle token refresh if access_token is missing but refresh_token exists
  const authData = await getServerAuthData();
  if (!authData) {
    redirect("/signin");
  }

  let paginatedTransactions: PaginatedData<Transaction> = {
    data: [],
    pagination: {
      limit: 10,
      cursor: undefined,
    } as Pagination,
  };

  try {
    const res = extractCurrentUserV1(await getCurrentUserV1(authData.accessToken));
    if (res) {
      user = res;

      if (user.wallet) {
        wallet = user.wallet;
      } else {
        wallet = { ...INITIAL_WALLET, user_id: user.id };
      }

      const transactions = await getTransactionsV1(
        {
          paginate: "PAGE" as const,
          page: 1,
          limit: 10,
          cursor: undefined,
          status: "SUCCESS",
        },
        authData.accessToken,
      );

      if (transactions.ok && transactions.result) {
        paginatedTransactions = transactions.result;
      }
    }
  } catch (err: any) {
    console.error("Server Error: Failed to fetch user wallet data:", err);
    // If error is auth-related, redirect to signin
    if (
      err?.message?.includes("401") ||
      err?.message?.includes("Unauthorized") ||
      err?.message?.includes("Token")
    ) {
      redirect("/signin");
    }
  }

  return (
    <div className="flex flex-col">
      <div className="mx-auto mt-4 w-full min-w-0 max-w-[900px] space-y-6 px-4 sm:px-6">
        <WalletBalanceSection
          balance={wallet.balance}
          currency={wallet.currency}
          initialProfile={user}
        />

        <WalletHistorySection paginatedTransactions={paginatedTransactions} />
      </div>
    </div>
  );
};
