import { Injectable } from '@nestjs/common';
import {
  decodeOffsetCursor,
  encodeCursor,
} from 'src/core/base/pagination.util';
import { TourStateMetaObjectType } from './accounting-arg.types';
import { AccountingState } from './accounting-state';
import { PaginatedTourObjectType } from './accounting.object-type';
import { AccountingService } from './accounting.service';
import { TicketService } from '../feat-business-objects/entities/ticket/ticket.service';
import { TourService } from '../feat-business-objects/entities/tour/tour.service';
import { TourAccountingFilterDto } from '../feat-business-objects/entities/tour/tours.filter';

@Injectable()
export class AccountingValidationService {
  constructor(
    private readonly accounting: AccountingService,
    private readonly ticketService: TicketService,
    private readonly tourService: TourService,
  ) {}

  async paginateToursByState(
    state: AccountingState,
    filter: TourAccountingFilterDto,
    take: number = 10,
    cursor?: string,
  ): Promise<PaginatedTourObjectType> {
    const skip = cursor ? decodeOffsetCursor(cursor) : 0;
    const { tours, total } = await this.tourService.findByAccountingState(
      state,
      filter,
      take,
      skip,
    );

    const prevPage = skip - take < 0 ? 0 : skip - take;
    const nextPage = skip + take < total ? skip + take : skip;

    return {
      nodes: tours,
      prevCursor: encodeCursor(prevPage),
      endCursor: encodeCursor(nextPage),
      hasNextPage: nextPage !== skip,
      totalCount: total,
    };
  }

  async getAccountingStateMeta(
    accountingState: AccountingState,
  ): Promise<TourStateMetaObjectType> {
    return this.tourService.calculateAccountingStateMeta(accountingState);
  }

  findTicketByTicketId(ticketId?: string | null) {
    if (!ticketId) return;
    return this.ticketService.findById(ticketId);
  }

  async getTourCostBreakdown(operationId: string) {
    return this.accounting.tourCostBreakdown(operationId);
  }
}
