/**
 * Sales Invoice History Page
 * Display list of all sales invoices with search and filtering
 * URL: /admin/sales/history
 */

import { Metadata } from 'next';
import { redirect } from 'next/navigation';
import { getSession } from '@/lib/auth';
import { handleListSalesInvoices } from '@/lib/actions/sales-invoice.actions';
import SalesInvoiceHistory from '@/components/admin/sales/sales-invoice-history';
import { getCurrencySymbolAsync } from '@/lib/server-currency';

export const metadata: Metadata = {
  title: 'Sales Invoice History | Sales Management',
  description: 'View all sales invoices',
};

interface SalesHistoryPageProps {
  searchParams?: Promise<{
    page?: string;
    search?: string;
    status?: string;
    documentType?: string;
  }>;
}

export default async function SalesHistoryPage({
  searchParams,
}: SalesHistoryPageProps) {
  const resolvedSearchParams = await searchParams;
  // Authentication check
  const session = await getSession();
  if (!session?.user) {
    redirect('/login');
  }

  const page = parseInt(resolvedSearchParams?.page || '1', 10);
  const pageSize = 25;
  const skip = (page - 1) * pageSize;

  // Fetch invoices — by default exclude pure shipment docs (SHP/) from the main list
  // since they are logistics-only and their amounts would double-count alongside ST/ invoices.
  // Admin can still filter to show shipments explicitly via documentType=shipment or documentType=all.
  const requestedDocType = resolvedSearchParams?.documentType;
  const explicitDocType =
    requestedDocType === 'shipment' ? 'shipment' as const
    : requestedDocType === 'tax_invoice' ? 'tax_invoice' as const
    : undefined;
  const showAll = requestedDocType === 'all';

  const result = await handleListSalesInvoices({
    skip,
    take: pageSize,
    search: resolvedSearchParams?.search,
    status: resolvedSearchParams?.status,
    documentType: explicitDocType,
    excludeShipments: !showAll && !explicitDocType,
  });

  const invoices = result.success ? result.data?.items || [] : [];
  const total = result.success ? result.data?.total || 0 : 0;
  const currencySymbol = await getCurrencySymbolAsync();

  return (
    <div className="space-y-4">
      <div>
        <h1 className="text-3xl font-bold">قائمة الفواتير</h1>
        <p className="text-muted-foreground mt-1">View and manage sales invoices</p>
      </div>

      {/* Sales Invoice History Component */}
      <SalesInvoiceHistory
        invoices={invoices}
        total={total}
        pageSize={pageSize}
        currentPage={page}
        search={resolvedSearchParams?.search}
        status={resolvedSearchParams?.status}
        documentType={resolvedSearchParams?.documentType}
        currencySymbol={currencySymbol}
      />
    </div>
  );
}
