/**
 * Service for fetching and managing requests data
 */

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

interface FetchRequestsOptions {
  page: number;
  itemsPerPage: number;
  filters?: RequestFilters;
  isOrgLevel: boolean;
}

export async function fetchRequestsData({
  page,
  itemsPerPage,
  filters,
  isOrgLevel
}: FetchRequestsOptions) {
  if (isOrgLevel) {
    // Organization-level: Use backend pagination with filters for list display
    // Build filter params for backend API (including status filter for list)
    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?.templateType === 'FORM_16') {
      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'; // Default to '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?.toISOString();
    if (filters?.endDate) backendFilters.endDate = filters.endDate?.toISOString();

    // Fetch paginated data for list display (with status filter)
    const pageResult = await workflowApi.listWorkflows({
      page,
      limit: itemsPerPage,
      ...backendFilters
    });

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

    // 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 = pageResult?.pagination || {
      page,
      limit: itemsPerPage,
      total: nonDraftData.length,
      totalPages: 1
    };

    // Stats will be fetched separately from backend stats API (always unfiltered)
    // No need to fetch all data for stats here - backend stats API handles it
    // Return empty array for allData - stats will come from backendStats
    const allDataForStats: any[] = [];

    return {
      data: nonDraftData, // Paginated data for list display (with status filter)
      allData: allDataForStats, // All data without status filter for stats calculation
      filteredData: nonDraftData, // Same as data for list
      pagination: {
        page: pagination.page,
        limit: pagination.limit || itemsPerPage,
        total: pagination.total || nonDraftData.length,
        totalPages: pagination.totalPages || 1
      }
    };
    } else {
      // User-level: Use SEPARATE endpoint for regular users' "All Requests" page
      // This shows ALL requests where user is involved:
      // - As initiator (created the request)
      // - As approver (in any approval level)
      // - As participant/spectator
      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?.templateType === 'FORM_16') {
        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?.slaCompliance && filters.slaCompliance !== 'all') backendFilters.slaCompliance = filters.slaCompliance;
      if (filters?.dateRange) backendFilters.dateRange = filters.dateRange;
      if (filters?.startDate) backendFilters.startDate = filters.startDate?.toISOString();
      if (filters?.endDate) backendFilters.endDate = filters.endDate?.toISOString();

      // Fetch paginated data using endpoint for regular users
      // This endpoint includes all requests where user is initiator, approver, or participant
      const pageResult = await workflowApi.listParticipantRequests({
        page,
        limit: itemsPerPage,
        ...backendFilters
      });

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

      // 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 = pageResult?.pagination || {
        page,
        limit: itemsPerPage,
        total: nonDraftData.length,
        totalPages: 1
      };

      return {
        data: nonDraftData, // Paginated data for list
        allData: [], // Stats come from backend stats API for user-level too
        filteredData: nonDraftData, // This is the data for the current page, already filtered
        pagination: pagination
      };
    }
}

export async function fetchAllRequestsForExport(isOrgLevel: boolean): Promise<any[]> {
  // Use a larger limit (100) to reduce number of API calls when exporting all data
  const EXPORT_FETCH_LIMIT = 100;
  const allPages: any[] = [];
  let currentPageNum = 1;
  let hasMore = true;
  const maxPages = 100;

  while (hasMore && currentPageNum <= maxPages) {
    const pageResult = isOrgLevel
      ? await workflowApi.listWorkflows({ page: currentPageNum, limit: EXPORT_FETCH_LIMIT }) // Admin: All org requests
      : await workflowApi.listParticipantRequests({ page: currentPageNum, limit: EXPORT_FETCH_LIMIT }); // Regular users: All requests where user is involved (initiator, approver, or participant)

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

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

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

  return allPages;
}
