/**
 * Service for fetching user requests data (initiator + participant)
 * OPTIMIZED: Uses single backend endpoint that now includes both initiator and participant requests
 * 
 * This service is specifically for regular users' "All Requests" page
 * Shows requests where user is EITHER initiator OR participant (approver/spectator)
 */

import workflowApi from '@/services/workflowApi';
import type { RequestFilters } from '../types/requests.types';

interface FetchUserAllRequestsOptions {
  page: number;
  itemsPerPage: number;
  filters?: RequestFilters;
}

/**
 * Fetch all requests for regular users (initiator + participant)
 * OPTIMIZED: Uses single listParticipantRequests endpoint which now includes initiator requests
 * Fetches only the requested page (10 records) for optimal performance
 */
export async function fetchUserParticipantRequestsData({
  page,
  itemsPerPage,
  filters
}: FetchUserAllRequestsOptions) {
  // Build filter params for backend API
  const backendFilters: any = {};
  if (filters?.search) backendFilters.search = filters.search;
  if (filters?.status && filters.status !== 'all') backendFilters.status = filters.status;
  if (filters?.priority && filters.priority !== 'all') backendFilters.priority = filters.priority;
  if (filters?.templateType && filters.templateType !== 'all') backendFilters.templateType = filters.templateType;
  if (filters?.financialYear) backendFilters.financialYear = filters.financialYear;
  if (filters?.quarter) backendFilters.quarter = filters.quarter;
  if (filters?.department && filters.department !== 'all') backendFilters.department = filters.department;
  if (filters?.initiator && filters.initiator !== 'all') backendFilters.initiator = filters.initiator;
  if (filters?.approver && filters.approver !== 'all') {
    backendFilters.approver = filters.approver;
    backendFilters.approverType = filters.approverType || 'current';
  }
  if (filters?.slaCompliance && filters.slaCompliance !== 'all') backendFilters.slaCompliance = filters.slaCompliance;
  if (filters?.dateRange) backendFilters.dateRange = filters.dateRange;
  if (filters?.startDate) backendFilters.startDate = filters.startDate instanceof Date ? filters.startDate.toISOString() : filters.startDate;
  if (filters?.endDate) backendFilters.endDate = filters.endDate instanceof Date ? filters.endDate.toISOString() : filters.endDate;

  // Use single optimized endpoint - listParticipantRequests now includes initiator requests
  // Only fetch the requested page (10 records) for optimal performance
  const result = await workflowApi.listParticipantRequests({
    page,
    limit: itemsPerPage,
    ...backendFilters
  });

  // Extract data from result
  let pageData: any[] = [];
  if (Array.isArray(result?.data)) {
    pageData = result.data;
  } else if (Array.isArray(result)) {
    pageData = result;
  }

  // Filter out drafts (backend should handle this, but double-check)
  const nonDraftData = pageData.filter((req: any) => {
    const reqStatus = (req.status || '').toString().toUpperCase();
    return reqStatus !== 'DRAFT';
  });

  // Get pagination info from backend response
  const pagination = result?.pagination || {
    page,
    limit: itemsPerPage,
    total: nonDraftData.length,
    totalPages: 1
  };

  return {
    data: nonDraftData,
    allData: [],
    filteredData: nonDraftData,
    pagination: {
      page: pagination.page,
      limit: pagination.limit || itemsPerPage,
      total: pagination.total || nonDraftData.length,
      totalPages: pagination.totalPages || 1
    }
  };
}

const EXPORT_FETCH_LIMIT = 100;

/**
 * Fetch all requests for export (regular users - initiator + participant)
 * OPTIMIZED: Uses single endpoint that includes both initiator and participant requests
 */
export async function fetchAllRequestsForExport(filters?: RequestFilters): Promise<any[]> {
  const allPages: any[] = [];
  let hasMore = true;
  let currentPage = 1;
  const maxPages = 100; // Safety limit

  // Build filter params for backend API
  const backendFilters: any = {};
  if (filters?.search) backendFilters.search = filters.search;
  if (filters?.status && filters.status !== 'all') backendFilters.status = filters.status;
  if (filters?.priority && filters.priority !== 'all') backendFilters.priority = filters.priority;
  if (filters?.templateType && filters.templateType !== 'all') backendFilters.templateType = filters.templateType;
  if (filters?.financialYear) backendFilters.financialYear = filters.financialYear;
  if (filters?.quarter) backendFilters.quarter = filters.quarter;
  if (filters?.department && filters.department !== 'all') backendFilters.department = filters.department;
  if (filters?.initiator && filters.initiator !== 'all') backendFilters.initiator = filters.initiator;
  if (filters?.approver && filters.approver !== 'all') {
    backendFilters.approver = filters.approver;
    backendFilters.approverType = filters.approverType || 'current';
  }
  if (filters?.slaCompliance && filters.slaCompliance !== 'all') backendFilters.slaCompliance = filters.slaCompliance;
  if (filters?.dateRange) backendFilters.dateRange = filters.dateRange;
  if (filters?.startDate) backendFilters.startDate = filters.startDate instanceof Date ? filters.startDate.toISOString() : filters.startDate;
  if (filters?.endDate) backendFilters.endDate = filters.endDate instanceof Date ? filters.endDate.toISOString() : filters.endDate;

  // Fetch all pages using the single optimized endpoint
  while (hasMore && currentPage <= maxPages) {
    const pageResult = await workflowApi.listParticipantRequests({
      page: currentPage,
      limit: EXPORT_FETCH_LIMIT,
      ...backendFilters
    });

    let pageData: any[] = [];
    if (Array.isArray(pageResult?.data)) {
      pageData = pageResult.data;
    } else if (Array.isArray(pageResult)) {
      pageData = pageResult;
    }

    if (pageData.length === 0) {
      hasMore = false;
    } else {
      // Filter out drafts
      const nonDraftData = pageData.filter((req: any) => {
        const reqStatus = (req.status || '').toString().toUpperCase();
        return reqStatus !== 'DRAFT';
      });
      allPages.push(...nonDraftData);
      currentPage++;

      if (pageResult?.pagination) {
        hasMore = currentPage <= pageResult.pagination.totalPages;
      } else {
        hasMore = pageData.length === EXPORT_FETCH_LIMIT;
      }
    }
  }

  return allPages;
}

