"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UserLocationService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("typeorm");
const typeorm_2 = require("@nestjs/typeorm");
const userlocation_entity_1 = require("../../common/userlocation/userlocation.entity");
const userlocationhistory_entity_1 = require("../../common/userlocation/userlocationhistory.entity");
let UserLocationService = class UserLocationService {
    constructor(userLocationRepository, userLocationRepositoryHistory) {
        this.userLocationRepository = userLocationRepository;
        this.userLocationRepositoryHistory = userLocationRepositoryHistory;
    }
    async updateDriverLocation(updateLocationDto) {
        const userId = updateLocationDto.userId;
        const user = await this.userLocationRepository.findOne({ where: { userId: userId } });
        if (!user) {
            const location = this.userLocationRepository.create({
                userId: userId,
                latitude: updateLocationDto.latitude,
                longitude: updateLocationDto.longitude,
            });
            this.userLocationRepository.save(location);
        }
        else {
            user.latitude = updateLocationDto.latitude;
            user.longitude = updateLocationDto.longitude;
            await this.userLocationRepository.save(user);
        }
        const locationHistory = this.userLocationRepositoryHistory.create({
            userId: userId,
            latitude: updateLocationDto.latitude,
            longitude: updateLocationDto.longitude,
        });
        await this.userLocationRepositoryHistory.save(locationHistory);
        return user;
    }
    async getDriverCurrentLocation(userId) {
        return this.userLocationRepository.findOne({
            where: { userId: userId }
        });
    }
    async getDriverLocationHistory(userId) {
        return this.userLocationRepositoryHistory.find({
            where: { userId: userId },
            order: { id: 'DESC' },
        });
    }
    async getNearbyDrivers(latitude, longitude, radius, service) {
        const query = this.userLocationRepository
            .createQueryBuilder("ul")
            .innerJoin("driver", "dr", "dr.userId = ul.userId")
            .innerJoin("shops", "sp", "sp.id = dr.shopId")
            .innerJoin("users", "u", "u.id = ul.userId")
            .where(`
          ST_Distance_Sphere(
            point(ul.longitude, ul.latitude),
            point(:lng, :lat)
          ) <= :radiusInMeters
          `, {
            lat: latitude,
            lng: longitude,
            radiusInMeters: radius * 1000,
        })
            .andWhere("dr.online = :online", { online: 1 })
            .select([
            "ul.id AS locationId",
            "ul.latitude AS latitude",
            "ul.longitude AS longitude",
            "u.id AS userId",
            "u.name AS name",
            "u.lastName AS lastName",
            "u.email AS email",
            "u.mobileNumber AS mobileNumber",
            "dr.services AS dr_services",
            "sp.name as shop_name",
            "sp.image as shop_image",
            `ROUND(ST_Distance_Sphere(
          point(ul.longitude, ul.latitude),
          point(:lng, :lat)
        ) / 1000, 2) AS distance`
        ])
            .setParameters({ lat: latitude, lng: longitude });
        if (service) {
            query.andWhere("FIND_IN_SET(:service, dr.services)", { service });
        }
        const drivers = await query.getRawMany();
        return drivers;
    }
};
exports.UserLocationService = UserLocationService;
exports.UserLocationService = UserLocationService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_2.InjectRepository)(userlocation_entity_1.UserLocation)),
    __param(1, (0, typeorm_2.InjectRepository)(userlocationhistory_entity_1.UserLocationHistory)),
    __metadata("design:paramtypes", [typeorm_1.Repository,
        typeorm_1.Repository])
], UserLocationService);
//# sourceMappingURL=userlocation.service.js.map