import { Inject, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { RiderCordinates } from './rider-cordinates.entity';
import { Repository } from 'typeorm';
import { CreateCordinatesDTO } from './dto/create-cordinates.dto';
import { ClientProxy } from '@nestjs/microservices';
import { firstValueFrom } from 'rxjs';

@Injectable()
export class RiderCordinatesService {
  constructor(
    @InjectRepository(RiderCordinates)
    private riderRepo: Repository<RiderCordinates>,
    @Inject('RIDERS') private client: ClientProxy,
  ) {}

  async saveCordinates(dto: CreateCordinatesDTO): Promise<RiderCordinates> {
    const newrecord = this.riderRepo.create(dto); //this creates the new entity instance based on the DTO data
    return this.riderRepo.save(newrecord);
  }

  async getAll(): Promise<RiderCordinates[]> {
    return this.riderRepo.find();
  }

  async getById(id: number): Promise<any> {
    const coordinates = await this.riderRepo.findOne({ where: { id } });
    console.log('coordinates : ', coordinates);
    const pattern = { cmd: 'get-rider' };
    const payload = { id: id };
    const rider = await firstValueFrom(this.client.send(pattern, payload));
    return { coordinates, rider };
  }
}
