import { DefaultApi, Petition, RestOutputBean } from '@/openapi/mz-resend';
import { AxiosResponse } from 'axios';
import { ResendResponse } from '@services/mz/LostPetitionService';
import type { PaginatedResponse } from '@interfaces/base/PaginatedResponse';
import { toUtcTimestamp } from '@utils/format-date';
import { PetitionInfo } from '@openapi/mz-history';
import { TableFilter } from '@models/base/TableFilter';

class LostStatementService {
  async getPaginated(
    filter: TableFilter
  ): Promise<PaginatedResponse<PetitionInfo>> {
    const { data } = await new DefaultApi().lostRequests(
      filter.pagination.rowsPerPage,
      filter.pagination.page,
      filter.dateFrom ? toUtcTimestamp(filter.dateFrom) : undefined,
      filter.dateTo ? toUtcTimestamp(filter.dateTo) : undefined,
      filter.search ? (filter.search as string)?.trim() : undefined
    );
    const { values = [], ...responseFilter } = data;

    return {
      items: values,
      pagination: {
        ...filter.pagination,
        rowsPerPage: responseFilter.limit ?? 0,
        rowsNumber: responseFilter.total as number,
        page: responseFilter.offset ?? 0,
      },
    };
  }

  async resend(
    statements: Petition[],
    forceSend = true
  ): Promise<ResendResponse> {
    const result = await Promise.allSettled(
      statements.map((s) =>
        new DefaultApi().request({
          messageId: s.id,
          forceSend,
        })
      )
    );

    const resentItems: RestOutputBean[] = [];
    const failedItems: RestOutputBean[] = [];
    result.forEach((el) => {
      if (el.status === 'fulfilled' && el.value.status.toString()[0] === '2') {
        resentItems.push(el.value.data);
      } else {
        failedItems.push(
          (el as PromiseFulfilledResult<AxiosResponse<RestOutputBean>>)?.value
            ?.data ?? {}
        );
      }
    });

    return {
      resentItems,
      failedItems,
    };
  }
}
export default new LostStatementService();
