import { FastifyPluginAsync } from 'fastify' import { db } from '../db' type SlugParam = { Params: { slug: string } } type SlugIdParam = { Params: { slug: string; id: string } } const rooms: FastifyPluginAsync = async (fastify) => { const getHotelId = async (slug: string): Promise => { const { rows } = await db.query('SELECT id FROM hotels WHERE slug = $1', [slug]) return rows[0]?.id ?? null } const canAccess = (userSlug: string | null, role: string, slug: string) => role === 'super_admin' || userSlug === slug // ── GET /api/hotels/:slug/rooms ──────────────────────────────────────────── fastify.get( '/api/hotels/:slug/rooms', { onRequest: [fastify.authenticate] }, async (request, reply) => { const { slug } = request.params if (!canAccess(request.user.hotelSlug, request.user.role, slug)) { return reply.code(403).send({ error: 'Forbidden' }) } const hotelId = await getHotelId(slug) if (!hotelId) return reply.code(404).send({ error: 'Hotel not found' }) const { rows } = await db.query( `SELECT r.*, (SELECT json_build_object( 'guest_name', b.guest_name, 'check_in', b.check_in, 'check_out', b.check_out, 'status', b.status ) FROM bookings b WHERE b.room_id = r.id AND b.status = 'checked_in' LIMIT 1 ) AS current_booking FROM rooms r WHERE r.hotel_id = $1 ORDER BY r.floor, r.number`, [hotelId], ) return rows }, ) // ── POST /api/hotels/:slug/rooms ─────────────────────────────────────────── fastify.post( '/api/hotels/:slug/rooms', { onRequest: [fastify.authenticate] }, async (request, reply) => { if (!['manager', 'hotel_admin', 'super_admin'].includes(request.user.role)) { return reply.code(403).send({ error: 'Forbidden' }) } const { slug } = request.params if (!canAccess(request.user.hotelSlug, request.user.role, slug)) { return reply.code(403).send({ error: 'Forbidden' }) } const hotelId = await getHotelId(slug) if (!hotelId) return reply.code(404).send({ error: 'Hotel not found' }) const { number, type, floor = 1, max_guests = 2, base_rate, amenities = [], name, category_id, bed_type = 'double', beds, housekeeping_status = 'clean', sort_order = 99, allow_hourly = false, hourly_rate, extra_place, child_policy, description, photos = [], early_checkin_fee, late_checkout_fee, } = request.body const { rows } = await db.query( `INSERT INTO rooms (hotel_id, number, type, floor, max_guests, base_rate, amenities, name, category_id, bed_type, beds, housekeeping_status, sort_order, allow_hourly, hourly_rate, extra_place, child_policy, description, photos, early_checkin_fee, late_checkout_fee) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21) RETURNING *`, [ hotelId, number, type, floor, max_guests, base_rate, amenities, name ?? null, category_id ?? null, bed_type, beds ? JSON.stringify(beds) : null, housekeeping_status, sort_order, allow_hourly, hourly_rate ?? null, extra_place ? JSON.stringify(extra_place) : null, child_policy ? JSON.stringify(child_policy) : null, description ?? null, photos, early_checkin_fee ?? null, late_checkout_fee ?? null, ], ) return reply.code(201).send(rows[0]) }, ) // ── GET /api/hotels/:slug/rooms/:id ─────────────────────────────────────── fastify.get( '/api/hotels/:slug/rooms/:id', { onRequest: [fastify.authenticate] }, async (request, reply) => { const { slug, id } = request.params if (!canAccess(request.user.hotelSlug, request.user.role, slug)) { return reply.code(403).send({ error: 'Forbidden' }) } const hotelId = await getHotelId(slug) if (!hotelId) return reply.code(404).send({ error: 'Hotel not found' }) const { rows } = await db.query( 'SELECT * FROM rooms WHERE id = $1 AND hotel_id = $2', [id, hotelId], ) if (!rows[0]) return reply.code(404).send({ error: 'Room not found' }) return rows[0] }, ) // ── PATCH /api/hotels/:slug/rooms/:id ───────────────────────────────────── fastify.patch }>( '/api/hotels/:slug/rooms/:id', { onRequest: [fastify.authenticate] }, async (request, reply) => { if (!['manager', 'hotel_admin', 'super_admin'].includes(request.user.role)) { return reply.code(403).send({ error: 'Forbidden' }) } const { slug, id } = request.params if (!canAccess(request.user.hotelSlug, request.user.role, slug)) { return reply.code(403).send({ error: 'Forbidden' }) } const hotelId = await getHotelId(slug) if (!hotelId) return reply.code(404).send({ error: 'Hotel not found' }) const allowed = [ 'number', 'type', 'floor', 'max_guests', 'base_rate', 'status', 'amenities', 'name', 'category_id', 'bed_type', 'beds', 'housekeeping_status', 'sort_order', 'allow_hourly', 'hourly_rate', 'extra_place', 'child_policy', 'description', 'photos', 'early_checkin_fee', 'late_checkout_fee', 'maintenance_from', 'maintenance_to', ] const updates: string[] = [] const values: unknown[] = [] let idx = 1 for (const key of allowed) { if (request.body[key] !== undefined) { updates.push(`${key} = $${idx}`) const val = request.body[key] values.push( (key === 'beds' || key === 'extra_place' || key === 'child_policy') && val && typeof val === 'object' ? JSON.stringify(val) : val, ) idx++ } } if (updates.length === 0) return reply.code(400).send({ error: 'Nothing to update' }) updates.push(`updated_at = NOW()`) values.push(id, hotelId) const { rows } = await db.query( `UPDATE rooms SET ${updates.join(', ')} WHERE id = $${idx} AND hotel_id = $${idx + 1} RETURNING *`, values, ) if (!rows[0]) return reply.code(404).send({ error: 'Room not found' }) return rows[0] }, ) // ── DELETE /api/hotels/:slug/rooms/:id ──────────────────────────────────── fastify.delete( '/api/hotels/:slug/rooms/:id', { onRequest: [fastify.authenticate] }, async (request, reply) => { if (!['manager', 'hotel_admin', 'super_admin'].includes(request.user.role)) { return reply.code(403).send({ error: 'Forbidden' }) } const { slug, id } = request.params if (!canAccess(request.user.hotelSlug, request.user.role, slug)) { return reply.code(403).send({ error: 'Forbidden' }) } const hotelId = await getHotelId(slug) if (!hotelId) return reply.code(404).send({ error: 'Hotel not found' }) const { rowCount } = await db.query( 'DELETE FROM rooms WHERE id = $1 AND hotel_id = $2', [id, hotelId], ) if (!rowCount) return reply.code(404).send({ error: 'Room not found' }) return reply.code(204).send() }, ) } export default rooms