import { db } from "@/db";
import { accountTransactions, bankAccounts, bankSettings, emailNotices, fundingRequests, paymentInstructions, supportMessages } from "@/db/schema";
import { isAdminAuthenticated } from "@/lib/admin-auth";
import { decryptSensitiveValue } from "@/lib/card-security";
import { and, desc, eq, gt } from "drizzle-orm";
import AdminDashboard from "./AdminDashboard";
import AdminLogin from "./AdminLogin";

export const dynamic = "force-dynamic";

export default async function AdminPage() {
  if (!(await isAdminAuthenticated())) return <AdminLogin />;

  const [accountRows, transactionRows, noticeRows, messageRows, settingsRows, processingRows, fundingRows] = await Promise.all([
    db.select({
      id: bankAccounts.id, accountNumber: bankAccounts.accountNumber, memberNumber: bankAccounts.memberNumber, userId: bankAccounts.userId,
      accountType: bankAccounts.accountType, currency: bankAccounts.currency, balance: bankAccounts.balance, apy: bankAccounts.apy, accountStatus: bankAccounts.accountStatus, openingDepositRequired: bankAccounts.openingDepositRequired, openingDepositDeclared: bankAccounts.openingDepositDeclared, fundingStatus: bankAccounts.fundingStatus,
      locked: bankAccounts.locked, lockReason: bankAccounts.lockReason, restricted: bankAccounts.restricted, restrictionReason: bankAccounts.restrictionReason, transfersBlocked: bankAccounts.transfersBlocked, transferRequirement: bankAccounts.transferRequirement, transferChallengeEnabled: bankAccounts.transferChallengeEnabled, transferChallengeType: bankAccounts.transferChallengeType, transferChallengeCodeEncrypted: bankAccounts.transferChallengeCodeEncrypted, transferChallengeProgress: bankAccounts.transferChallengeProgress, bitcoinDepositAddress: bankAccounts.bitcoinDepositAddress, usdtTrc20DepositAddress: bankAccounts.usdtTrc20DepositAddress,
      firstName: bankAccounts.firstName, middleName: bankAccounts.middleName, lastName: bankAccounts.lastName, dateOfBirth: bankAccounts.dateOfBirth,
      email: bankAccounts.email, phone: bankAccounts.phone, addressLine1: bankAccounts.addressLine1, addressLine2: bankAccounts.addressLine2,
      city: bankAccounts.city, stateProvince: bankAccounts.stateProvince, postalCode: bankAccounts.postalCode, country: bankAccounts.country,
      citizenship: bankAccounts.citizenship, taxIdLast4: bankAccounts.taxIdLast4, taxIdEncrypted: bankAccounts.taxIdEncrypted, occupation: bankAccounts.occupation, employer: bankAccounts.employer,
      sourceOfFunds: bankAccounts.sourceOfFunds, expectedActivity: bankAccounts.expectedActivity, beneficiaryName: bankAccounts.beneficiaryName,
      beneficiaryRelationship: bankAccounts.beneficiaryRelationship, eSignName: bankAccounts.eSignName, eSignedAt: bankAccounts.eSignedAt,
      governmentIdType: bankAccounts.governmentIdType, governmentIdLast4: bankAccounts.governmentIdLast4,
      identityDocumentName: bankAccounts.identityDocumentName, identityDocumentType: bankAccounts.identityDocumentType,
      status: bankAccounts.status, createdAt: bankAccounts.createdAt,
    }).from(bankAccounts).orderBy(desc(bankAccounts.createdAt)).limit(500),
    db.select().from(accountTransactions).orderBy(desc(accountTransactions.createdAt)).limit(500),
    db.select().from(emailNotices).orderBy(desc(emailNotices.createdAt)).limit(500),
    db.select().from(supportMessages).orderBy(desc(supportMessages.createdAt)).limit(500),
    db.select().from(bankSettings).limit(1),
    db.select({ id: paymentInstructions.id, accountId: paymentInstructions.accountId, reference: paymentInstructions.reference, amount: paymentInstructions.amount, currency: paymentInstructions.currency, recipientName: paymentInstructions.recipientName, processAfter: paymentInstructions.processAfter }).from(paymentInstructions).where(and(eq(paymentInstructions.status, "processing"), gt(paymentInstructions.processAfter, new Date()))).orderBy(desc(paymentInstructions.createdAt)),
    db.select().from(fundingRequests).orderBy(desc(fundingRequests.createdAt)).limit(500),
  ]);

  const accounts = accountRows.map(({ taxIdEncrypted, transferChallengeCodeEncrypted, ...row }) => ({ ...row, taxIdFull: taxIdEncrypted ? decryptSensitiveValue(taxIdEncrypted) : `Legacy record — only ending ${row.taxIdLast4} was retained`, activeChallengeCode: transferChallengeCodeEncrypted ? decryptSensitiveValue(transferChallengeCodeEncrypted) : null, eSignedAt: row.eSignedAt.toISOString(), createdAt: row.createdAt.toISOString() }));
  const transactions = transactionRows.map((row) => ({ ...row, createdAt: row.createdAt.toISOString() }));
  const notices = noticeRows.map((row) => ({ ...row, createdAt: row.createdAt.toISOString() }));
  const messages = messageRows.map((row) => ({ ...row, repliedAt: row.repliedAt?.toISOString() ?? null, appointmentAt: row.appointmentAt?.toISOString() ?? null, createdAt: row.createdAt.toISOString() }));

  return <AdminDashboard accounts={accounts} transactions={transactions} notices={notices} messages={messages} customerTheme={settingsRows[0]?.customerTheme ?? "ocean"} processingPayments={processingRows.map((row) => ({ ...row, processAfter: row.processAfter.toISOString() }))} minimumOpeningDeposit={settingsRows[0]?.minimumOpeningDeposit ?? "25.00"} fundingRequests={fundingRows.map(({checkImageData,...row})=>({...row,hasCheckImage:Boolean(checkImageData),reviewedAt:row.reviewedAt?.toISOString()??null,createdAt:row.createdAt.toISOString()}))} />;
}
