import { Router } from 'express';
import { prisma } from '../../lib/prisma.js';
import { z } from 'zod';
const router = Router();
// Validation schemas
const showtimeQuerySchema = z.object({
    movieId: z.string().optional(),
    date: z.string().optional(),
    hallId: z.string().optional()
});
// Get showtimes with filtering
router.get('/', async (req, res) => {
    try {
        const { movieId, date, hallId } = showtimeQuerySchema.parse(req.query);
        // Build where clause
        const where = {};
        if (movieId) {
            where.movieId = parseInt(movieId);
        }
        if (hallId) {
            where.hallId = parseInt(hallId);
        }
        if (date) {
            const startDate = new Date(date);
            const endDate = new Date(date);
            endDate.setDate(startDate.getDate() + 1);
            where.showDate = {
                gte: startDate,
                lt: endDate
            };
        }
        else {
            // Default to today and future showtimes
            where.showDate = {
                gte: new Date()
            };
        }
        const showtimes = await prisma.showtime.findMany({
            where,
            include: {
                movie: {
                    select: {
                        id: true,
                        title: true,
                        durationMin: true,
                        posterUrl: true,
                        genre: true
                    }
                },
                hall: {
                    select: {
                        id: true,
                        name: true,
                        capacity: true
                    }
                },
                bookings: {
                    select: {
                        seatLabel: true
                    }
                },
                _count: {
                    select: {
                        bookings: true
                    }
                }
            },
            orderBy: {
                showDate: 'asc'
            }
        });
        // Calculate available seats for each showtime
        const showtimesWithAvailability = showtimes.map(showtime => {
            const bookedSeats = showtime.bookings.map(booking => booking.seatLabel);
            const availableSeats = showtime.hall.capacity - showtime._count.bookings;
            return {
                ...showtime,
                basePrice: Number(showtime.basePrice),
                availableSeats,
                bookedSeats,
                isSoldOut: availableSeats <= 0
            };
        });
        res.json({
            success: true,
            data: { showtimes: showtimesWithAvailability }
        });
    }
    catch (error) {
        console.error('Error fetching showtimes:', error);
        if (error instanceof z.ZodError) {
            return res.status(400).json({
                success: false,
                message: 'Validation error',
                errors: error.issues
            });
        }
        res.status(500).json({
            success: false,
            message: 'Internal server error'
        });
    }
});
// Get showtime by ID
router.get('/:id', async (req, res) => {
    try {
        const showtimeId = parseInt(req.params.id);
        if (isNaN(showtimeId)) {
            return res.status(400).json({
                success: false,
                message: 'Invalid showtime ID'
            });
        }
        const showtime = await prisma.showtime.findUnique({
            where: { id: showtimeId },
            include: {
                movie: {
                    select: {
                        id: true,
                        title: true,
                        durationMin: true,
                        posterUrl: true,
                        genre: true,
                        synopsis: true
                    }
                },
                hall: {
                    select: {
                        id: true,
                        name: true,
                        capacity: true
                    }
                },
                bookings: {
                    select: {
                        seatLabel: true,
                        userId: true
                    }
                },
                _count: {
                    select: {
                        bookings: true
                    }
                }
            }
        });
        if (!showtime) {
            return res.status(404).json({
                success: false,
                message: 'Showtime not found'
            });
        }
        // Calculate available seats
        const bookedSeats = showtime.bookings.map(booking => booking.seatLabel);
        const availableSeats = showtime.hall.capacity - showtime._count.bookings;
        const showtimeWithAvailability = {
            ...showtime,
            basePrice: Number(showtime.basePrice),
            availableSeats,
            bookedSeats,
            isSoldOut: availableSeats <= 0
        };
        res.json({
            success: true,
            data: { showtime: showtimeWithAvailability }
        });
    }
    catch (error) {
        console.error('Error fetching showtime:', error);
        res.status(500).json({
            success: false,
            message: 'Internal server error'
        });
    }
});
// Get available seats for a showtime
router.get('/:id/seats', async (req, res) => {
    try {
        const showtimeId = parseInt(req.params.id);
        if (isNaN(showtimeId)) {
            return res.status(400).json({
                success: false,
                message: 'Invalid showtime ID'
            });
        }
        const showtime = await prisma.showtime.findUnique({
            where: { id: showtimeId },
            include: {
                hall: {
                    include: {
                        seats: {
                            orderBy: {
                                label: 'asc'
                            }
                        }
                    }
                },
                bookings: {
                    select: {
                        seatLabel: true
                    }
                }
            }
        });
        if (!showtime) {
            return res.status(404).json({
                success: false,
                message: 'Showtime not found'
            });
        }
        const bookedSeats = new Set(showtime.bookings.map(booking => booking.seatLabel));
        const seatsWithStatus = showtime.hall.seats.map(seat => ({
            ...seat,
            isAvailable: !bookedSeats.has(seat.label)
        }));
        res.json({
            success: true,
            data: {
                seats: seatsWithStatus,
                hall: {
                    id: showtime.hall.id,
                    name: showtime.hall.name,
                    capacity: showtime.hall.capacity
                }
            }
        });
    }
    catch (error) {
        console.error('Error fetching seats:', error);
        res.status(500).json({
            success: false,
            message: 'Internal server error'
        });
    }
});
export default router;
