"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.DriverService = void 0;
const common_1 = require("@nestjs/common");
const typeorm_1 = require("typeorm");
const typeorm_2 = require("@nestjs/typeorm");
const driver_entity_1 = require("../../common/driver/driver.entity");
const driver_status_history_entity_1 = require("../../common/driver/driver-status-history.entity");
const payment_entity_1 = require("../../common/payment/payment.entity");
const driver_review_entity_1 = require("../../common/driverreview/driver-review.entity");
let DriverService = class DriverService {
    constructor(driverRepository, driverStatusHistory, paymentsRepository, driverReviewRepository) {
        this.driverRepository = driverRepository;
        this.driverStatusHistory = driverStatusHistory;
        this.paymentsRepository = paymentsRepository;
        this.driverReviewRepository = driverReviewRepository;
    }
    async updateDriverOnlineStatus(updateDriverOnlineStatusDto) {
        const { driverId, online } = updateDriverOnlineStatusDto;
        const driver = await this.driverRepository.findOne({
            where: { user: { id: driverId } },
            relations: ['user'],
        });
        if (!driver) {
            throw new common_1.NotFoundException(`Driver with user ID ${driverId} not found`);
        }
        const history = this.driverStatusHistory.create({
            driver: driver.user,
            online,
        });
        await this.driverStatusHistory.save(history);
        driver.online = online;
        return await this.driverRepository.save(driver);
    }
    async getDriverStatusHistory(driverId) {
        return await this.driverStatusHistory.find({
            where: { driver: { id: driverId } },
            order: { timestamp: 'DESC' },
        });
    }
    async getDriverDetail(driverId) {
        const driver = await this.driverRepository
            .createQueryBuilder('driver')
            .leftJoin('users', 'user', 'user.id = driver.userId')
            .leftJoin('shops', 'shop', 'shop.id = driver.shopId')
            .select([
            'driver.online AS online',
            'driver.documents AS documents',
            'driver.vehicle_photo AS vehicle_photo',
            'driver.name_plate AS name_plate',
            'driver.dl_number AS dl_number',
            'driver.dl_expiry_date AS dl_expiry_date',
            'driver.experience AS experience',
            'driver.services AS services',
            'user.name AS name',
            'user.lastName AS lastName',
            'user.email AS email',
            'user.mobileNumber AS mobileNumber',
            'user.nationality AS nationality',
            'user.preferredLanguage AS preferredLanguage',
            'user.gender AS gender',
            'user.userPhoto AS userPhoto',
            'user.userAddress AS userAddress',
            'user.dateOfBirth AS dateOfBirth',
            'shop.id AS shop_id',
            'shop.name AS shop_name',
            'shop.address AS shop_address',
            'shop.latitude AS shop_latitude',
            'shop.longitude AS shop_longitude',
            'shop.logo AS shop_logo',
            'shop.image AS shop_image',
        ])
            .where('driver.userId = :driverId', { driverId })
            .getRawOne();
        if (!driver) {
            throw new common_1.NotFoundException(`Driver with ID ${driverId} not found`);
        }
        const totalStats = await this.paymentsRepository
            .createQueryBuilder('payment')
            .select('SUM(payment.totalMinutes)', 'total_minutes')
            .addSelect('SUM(payment.totalKm)', 'total_km')
            .addSelect('COUNT(payment.id)', 'total_trips')
            .where('payment.driverId = :driverId', { driverId })
            .getRawOne();
        const overallStats = await this.paymentsRepository
            .createQueryBuilder('payment')
            .select('SUM(payment.amount)', 'total_amount')
            .addSelect('SUM(payment.totalMinutes)', 'total_minutes')
            .addSelect('SUM(payment.totalKm)', 'total_km')
            .addSelect('COUNT(payment.id)', 'total_trips')
            .where('payment.driverId = :driverId', { driverId })
            .getRawOne();
        const todayStatsRaw = await this.paymentsRepository
            .createQueryBuilder('payment')
            .select('SUM(payment.amount)', 'today_amount')
            .addSelect('SUM(payment.totalMinutes)', 'today_minutes')
            .addSelect('SUM(payment.totalKm)', 'today_km')
            .addSelect('COUNT(payment.id)', 'today_trips')
            .where('payment.driverId = :driverId', { driverId })
            .andWhere('DATE(payment.createdAt) = CURDATE()')
            .getRawOne();
        const todayStats = {
            today_amount: Number(todayStatsRaw.today_amount) || 0,
            today_minutes: (Number(todayStatsRaw.today_minutes) || 0) / 60,
            today_km: Number(todayStatsRaw.today_km) || 0,
            today_trips: Number(todayStatsRaw.today_trips) || 0,
        };
        const ratingStats = await this.driverReviewRepository
            .createQueryBuilder('review')
            .select('AVG(review.rating)', 'avg_rating')
            .addSelect('COUNT(review.id)', 'total_reviews')
            .where('review.driverId = :driverId', { driverId })
            .andWhere('review.status = :status', { status: 'active' })
            .getRawOne();
        const total_hours = totalStats?.total_minutes
            ? (Number(totalStats.total_minutes) / 60).toFixed(2)
            : '0.00';
        const today_hours = todayStats?.today_minutes
            ? (Number(todayStats.today_minutes) / 60).toFixed(2)
            : '0.00';
        const avg_rating = ratingStats?.avg_rating
            ? Number(ratingStats.avg_rating).toFixed(2)
            : '0.00';
        const total_reviews = Number(ratingStats?.total_reviews || 0);
        return {
            driver,
            rating: {
                avg_rating,
                total_reviews,
            },
            overallStats,
            todayStats
        };
    }
};
exports.DriverService = DriverService;
exports.DriverService = DriverService = __decorate([
    (0, common_1.Injectable)(),
    __param(0, (0, typeorm_2.InjectRepository)(driver_entity_1.Driver)),
    __param(1, (0, typeorm_2.InjectRepository)(driver_status_history_entity_1.DriverStatusHistory)),
    __param(2, (0, typeorm_2.InjectRepository)(payment_entity_1.Payment)),
    __param(3, (0, typeorm_2.InjectRepository)(driver_review_entity_1.DriverReview)),
    __metadata("design:paramtypes", [typeorm_1.Repository,
        typeorm_1.Repository,
        typeorm_1.Repository,
        typeorm_1.Repository])
], DriverService);
//# sourceMappingURL=driver.service.js.map