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';

@Injectable()
export class OutBidLogsService {
  constructor(
    @InjectRepository(OutBidLog)
    readonly outbidLogRepo: Repository<OutBidLog>,
  ) {}

  async index(query: PaginateQuery) {
    const filterableColumns: {
      [key in Column<OutBidLog> | (string & {})]?:
        | (FilterOperator | FilterSuffix)[]
        | true;
    } = {
      id: true,
      lot_id: true,
      model: true,
      out_price: true,
      raw_data: true,
    };

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

    const data = await paginate(query, this.outbidLogRepo, {
      sortableColumns: ['id', 'lot_id', 'model', 'raw_data', 'out_price'],
      searchableColumns: ['id', 'lot_id', 'model', 'raw_data', 'out_price'],
      defaultLimit: 15,
      filterableColumns,
      defaultSortBy: [['id', 'DESC']],
      maxLimit: 100,
    });

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

  async create(data: CreateOutBidLogDto[]) {
    try {
      const result = await this.outbidLogRepo.upsert(data, {
        conflictPaths: ['model', 'lot_id'],
        skipUpdateIfNoValuesChanged: true,
      });

      if (!result) throw new BadRequestException(AppResponse.toResponse(false));

      return AppResponse.toResponse(true);
    } catch (error) {
      throw new BadRequestException(AppResponse.toResponse(false));
    }
  }

  async createSimple({ model, lot_id, ...data }: CreateOutBidLogDto) {
    const prev = await this.outbidLogRepo.findOne({
      where: { lot_id: lot_id, model: model },
    });

    if (!prev) {
      const result = await this.outbidLogRepo.save({ ...data, lot_id, model });

      return AppResponse.toResponse(!!result);
    }

    const result = await this.outbidLogRepo.update(
      { model: model, lot_id: lot_id },
      { ...data },
    );

    return AppResponse.toResponse(!!result);
  }
}
