import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { OutBidLog } from '../entities/out-bid-log.entity';
import AppResponse from 'src/response/app-response';
import {
  FilterOperator,
  FilterSuffix,
  paginate,
  PaginateQuery,
} from 'nestjs-paginate';
import { Column } from 'nestjs-paginate/lib/helper';
import { CreateOutBidLogDto } from '../dto/out-bid-log/create-out-bid-log.dto';
import { SendMessageHistory } from '../entities/send-message-histories.entity';
import { BotTelegramApi } from '../apis/bot-telegram.api';
import { BidsService } from './bids.service';

@Injectable()
export class SendMessageHistoriesService {
  constructor(
    @InjectRepository(SendMessageHistory)
    readonly sendMessageRepo: Repository<SendMessageHistory>,
    private readonly botTelegramApi: BotTelegramApi,
    private readonly bidsService: BidsService,
  ) {}

  async index(query: PaginateQuery) {
    const filterableColumns: {
      [key in Column<SendMessageHistory> | (string & {})]?:
        | (FilterOperator | FilterSuffix)[]
        | true;
    } = {
      id: true,
      message: true,
      'bid.name': true,
      'bid.lot_id': true,
    };

    query.filter = AppResponse.processFilters(query.filter, filterableColumns);

    const data = await paginate(query, this.sendMessageRepo, {
      sortableColumns: ['id', 'message', 'bid.name'],
      searchableColumns: ['id', 'message', 'bid.name'],
      defaultLimit: 15,
      filterableColumns,
      defaultSortBy: [['id', 'DESC']],
      relations: {
        bid: true,
      },
      maxLimit: 100,
    });

    return AppResponse.toPagination<SendMessageHistory>(
      data,
      true,
      SendMessageHistory,
    );
  }

  async sendTestMessage() {
    const date = new Date().toUTCString();

    const mockBid = this.bidsService.bidsRepo.create({
      id: 12345,
      max_price: 5000,
      reserve_price: 1000,
      current_price: 1200,
      name: 'Laptop Gaming ASUS ROG',
      quantity: 1,
      url: 'https://example.com/product/12345',
      model: 'ROG Strix G15',
      lot_id: 'LOT-67890',
      plus_price: 50,
      close_time: date,
      start_bid_time: date,
      first_bid: false,
      status: 'biding',
      histories: [
        {
          id: 1,
          price: 1000,
          created_at: date,
          updated_at: date,
        },
        {
          id: 2,
          price: 1100,
          created_at: date,
          updated_at: date,
        },
        {
          id: 3,
          price: 1200,
          created_at: date,
          updated_at: date,
        },
      ],
      created_at: date,
      updated_at: date,
    });

    const result = await this.botTelegramApi.sendBidInfo(mockBid);

    return AppResponse.toResponse(result);
  }
}
