"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.BookingController = void 0;
const common_1 = require("@nestjs/common");
const swagger_1 = require("@nestjs/swagger");
const booking_service_1 = require("./booking.service");
const booking_dto_1 = require("./booking.dto");
const booking_gateway_1 = require("../../common/booking/booking.gateway");
const firebase_service_1 = require("../fcm/firebase.service");
const user_services_1 = require("../user/user.services");
let BookingController = class BookingController {
    constructor(bookingService, bookingGateway, firebaseService, userService) {
        this.bookingService = bookingService;
        this.bookingGateway = bookingGateway;
        this.firebaseService = firebaseService;
        this.userService = userService;
    }
    async requestBooking(createBookingRequestDto) {
        try {
            const res = await this.bookingService.bookingRequest(createBookingRequestDto);
            if (res.length) {
                for (const req of res) {
                    this.bookingGateway.sendNotification({
                        driverId: req.driverId,
                        bookingDetail: req,
                        message: 'New booking request!',
                    });
                    const driver = await this.userService.findById(req.driverId);
                    const user = await this.userService.findById(req.userId);
                    if (driver.deviceId) {
                        try {
                            await this.firebaseService.sendNotification(driver.deviceId, 'New Booking Request 🚗', `You have a new booking request from ${user.name}.`, 'BookingRequests');
                        }
                        catch (fcmError) {
                            console.error('FCM notification failed:', fcmError?.message ?? fcmError);
                        }
                    }
                }
                return {
                    status: true,
                    message: "Successfully requested.",
                };
            }
            else {
                return {
                    status: false,
                    message: "Drivers not found.",
                };
            }
        }
        catch (error) {
            throw new common_1.BadRequestException(error.message);
        }
    }
    async getBookingRequests(driverId, status, scheduleType) {
        try {
            let validScheduleType = undefined;
            if (scheduleType === 'now' || scheduleType === 'schedule') {
                validScheduleType = scheduleType;
            }
            const res = await this.bookingService.getBookingRequests(driverId, status, validScheduleType);
            return {
                status: true,
                bookingRequests: res,
                message: "Booking Request lists.",
            };
        }
        catch (error) {
            throw new common_1.BadRequestException(error.message);
        }
    }
    async getOngoingBookings(driverId, scheduleType) {
        try {
            let validScheduleType = undefined;
            if (scheduleType === 'now' || scheduleType === 'schedule') {
                validScheduleType = scheduleType;
            }
            const res = await this.bookingService.getOnGoingBookingRequests(driverId, validScheduleType);
            return {
                status: true,
                bookingRequests: res,
                message: "Booking Request lists.",
            };
        }
        catch (error) {
            throw new common_1.BadRequestException(error.message);
        }
    }
    async confirmBooking(confirmBookingRequestDto) {
        try {
            const res = await this.bookingService.confirmBooking(confirmBookingRequestDto.driverId, confirmBookingRequestDto.requestId);
            const driver = await this.userService.findById(confirmBookingRequestDto.driverId);
            const user = await this.userService.findById(res.userId);
            if (user.deviceId) {
                try {
                    await this.firebaseService.sendNotification(user.deviceId, 'Booking Confirmed 🚗', `Your booking has been confirmed by ${driver.name}.`, 'BookingRequests');
                }
                catch (fcmError) {
                    console.error('FCM notification failed:', fcmError?.message ?? fcmError);
                }
            }
            this.bookingGateway.sendNotification({
                bookingDetail: res,
                message: 'Booking confirm!',
            });
            return {
                status: true,
                booking: res,
                message: "Successfully confirm.",
            };
        }
        catch (error) {
            throw new common_1.BadRequestException(error.message);
        }
    }
    async updateBookingStatus(updateBookingStatusDto) {
        try {
            const updatedBooking = await this.bookingService.updateBookingStatus(updateBookingStatusDto.bookingId, updateBookingStatusDto.status);
            try {
                const driver = await this.userService.findById(updatedBooking.driverId);
                const user = await this.userService.findById(updatedBooking.userId);
                if (user.deviceId) {
                    await this.firebaseService.sendNotification(user.deviceId, 'Booking Status Update 🚗', `Your booking status has been updated by ${driver.name}.`, 'BookingRequests');
                }
            }
            catch (fcmError) {
                console.error('FCM notification failed:', fcmError.message);
            }
            this.bookingGateway.sendStatusNotification({
                bookingDetail: updatedBooking,
                message: 'status update!',
            });
            return {
                bookingDetail: updatedBooking,
                status: true,
                message: 'Booking status updated successfully',
            };
        }
        catch (error) {
            throw new common_1.BadRequestException(error.message);
        }
    }
    async getBookingDetail(userId) {
        try {
            const res = await this.bookingService.getBookingDetail(userId);
            return {
                status: true,
                bookingDetail: res,
                message: "Booking detail fetched successfully.",
            };
        }
        catch (error) {
            throw new common_1.BadRequestException(error.message);
        }
    }
    async notify() {
        this.bookingGateway.sendNotification({
            user: 'Server',
            message: '🚀 New booking available!',
        });
        return {
            status: true,
            message: 'Notification sent to connected clients',
        };
    }
    sendMessage(body) {
        console.log('📩 Received via POST:', body);
        const user = body.user || 'Anonymous';
        const text = body.text || 'Hello from server!';
        this.bookingGateway.sendNotification({ user, text });
        return { status: true, message: 'Message sent', data: { user, text } };
    }
};
exports.BookingController = BookingController;
__decorate([
    (0, common_1.Post)('request'),
    __param(0, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [booking_dto_1.CreateBookingRequestDto]),
    __metadata("design:returntype", Promise)
], BookingController.prototype, "requestBooking", null);
__decorate([
    (0, common_1.Get)('request'),
    (0, swagger_1.ApiQuery)({ name: 'driverId', type: Number, description: 'Send Driver id for get request list', required: true }),
    (0, swagger_1.ApiQuery)({ name: 'status', type: String, description: 'Send status for get request list', required: true }),
    (0, swagger_1.ApiQuery)({ name: 'scheduleType', type: String, description: 'Send type for get request list', required: false }),
    __param(0, (0, common_1.Query)('driverId')),
    __param(1, (0, common_1.Query)('status')),
    __param(2, (0, common_1.Query)('scheduleType')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Number, String, String]),
    __metadata("design:returntype", Promise)
], BookingController.prototype, "getBookingRequests", null);
__decorate([
    (0, common_1.Get)('ongoingbooking'),
    (0, swagger_1.ApiQuery)({ name: 'driverId', type: Number, description: 'Send Driver id for get ongoing booking list', required: true }),
    (0, swagger_1.ApiQuery)({ name: 'scheduleType', type: String, description: 'Send type for get ongoing booking list', required: false }),
    __param(0, (0, common_1.Query)('driverId')),
    __param(1, (0, common_1.Query)('scheduleType')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Number, String]),
    __metadata("design:returntype", Promise)
], BookingController.prototype, "getOngoingBookings", null);
__decorate([
    (0, common_1.Post)('confirm'),
    __param(0, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [booking_dto_1.ConfirmBookingRequestDto]),
    __metadata("design:returntype", Promise)
], BookingController.prototype, "confirmBooking", null);
__decorate([
    (0, common_1.Patch)('status'),
    __param(0, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [booking_dto_1.UpdateBookingStatusDto]),
    __metadata("design:returntype", Promise)
], BookingController.prototype, "updateBookingStatus", null);
__decorate([
    (0, common_1.Get)('detail/:userId'),
    __param(0, (0, common_1.Param)('userId')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Number]),
    __metadata("design:returntype", Promise)
], BookingController.prototype, "getBookingDetail", null);
__decorate([
    (0, common_1.Get)('notify'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], BookingController.prototype, "notify", null);
__decorate([
    (0, common_1.Post)('send-message'),
    __param(0, (0, common_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", void 0)
], BookingController.prototype, "sendMessage", null);
exports.BookingController = BookingController = __decorate([
    (0, common_1.Controller)("app/booking"),
    __metadata("design:paramtypes", [booking_service_1.BookingService,
        booking_gateway_1.BookingGateway,
        firebase_service_1.FirebaseService,
        user_services_1.UserService])
], BookingController);
//# sourceMappingURL=booking.controller.js.map