import { FastifyPluginAsync } from 'fastify' import { db } from '../db' type SlugParam = { Params: { slug: string } } const hotelSettings: 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/hotel-settings ───────────────────────────────── fastify.get( '/api/hotels/:slug/hotel-settings', { 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: settingsRows }, { rows: hotelRows }] = await Promise.all([ db.query('SELECT key, value FROM hotel_settings WHERE hotel_id = $1', [hotelId]), db.query('SELECT check_in_time, check_out_time FROM hotels WHERE id = $1', [hotelId]), ]) const out: Record = {} for (const row of settingsRows) { out[row.key] = row.value } if (hotelRows[0]) { out.check_in_time = hotelRows[0].check_in_time out.check_out_time = hotelRows[0].check_out_time } return out }, ) // ── PATCH /api/hotels/:slug/hotel-settings ─────────────────────────────── fastify.patch }>( '/api/hotels/:slug/hotel-settings', { 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 updates = request.body for (const [key, value] of Object.entries(updates)) { await db.query( `INSERT INTO hotel_settings (hotel_id, key, value, updated_at) VALUES ($1, $2, $3::jsonb, NOW()) ON CONFLICT (hotel_id, key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()`, [hotelId, key, JSON.stringify(value)], ) } return { ok: true } }, ) } export default hotelSettings