Add database integration, auth API, admin/user portals, and deploy-db.sh

This commit is contained in:
2026-06-27 16:40:58 -05:00
parent 26559d4cf8
commit cc59177a74
25 changed files with 1423 additions and 118 deletions
+59 -40
View File
@@ -2,65 +2,84 @@
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/hooks/useAuth';
const IMAGES_KEY = 'la-huasca-admin-images';
interface ImageRecord {
id: number;
filename: string;
data: string;
uploaded_at: string;
}
export default function AdminPage() {
const { isAdmin, hydrated } = useAuth();
const router = useRouter();
const [images, setImages] = useState<string[]>([]);
const [images, setImages] = useState<ImageRecord[]>([]);
const [count, setCount] = useState(0);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!hydrated) return;
if (!isAdmin) {
router.push('/login');
return;
}
const stored = localStorage.getItem(IMAGES_KEY);
if (stored) {
try {
setImages(JSON.parse(stored));
} catch {
setImages([]);
}
}
}, [isAdmin, hydrated, router]);
useEffect(() => {
localStorage.setItem(IMAGES_KEY, JSON.stringify(images));
}, [images]);
fetch('/api/admin/images', { credentials: 'same-origin' })
.then(async (res) => {
if (!res.ok) {
if (res.status === 401) {
router.push('/login');
return;
}
throw new Error('Failed to load images');
}
const data = await res.json();
setImages(data.images || []);
setCount(data.count || 0);
})
.catch((err) => setError(err.message))
.finally(() => setLoading(false));
}, [router]);
const handleUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files;
if (!files) return;
Array.from(files).forEach((file) => {
const reader = new FileReader();
reader.onload = () => {
const result = reader.result as string;
setImages((prev) => [...prev, result]);
reader.onload = async () => {
const data = reader.result as string;
const res = await fetch('/api/admin/images', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ filename: file.name, data }),
credentials: 'same-origin',
});
if (!res.ok) {
setError('Upload failed');
return;
}
const result = await res.json();
setImages((prev) => [result.image, ...prev]);
setCount((prev) => prev + 1);
};
reader.readAsDataURL(file);
});
e.target.value = '';
};
const handleDelete = (index: number) => {
setImages((prev) => prev.filter((_, i) => i !== index));
const handleDelete = async (id: number) => {
const res = await fetch(`/api/admin/images?id=${id}`, {
method: 'DELETE',
credentials: 'same-origin',
});
if (res.ok) {
setImages((prev) => prev.filter((img) => img.id !== id));
setCount((prev) => prev - 1);
}
};
if (!hydrated || !isAdmin) {
return (
<main style={{ padding: '2rem' }}>
<p>Please log in as admin to access this page.</p>
</main>
);
}
if (loading) return <main style={{ padding: '2rem' }}><p>Loading...</p></main>;
return (
<main style={{ padding: '2rem' }}>
<h1>Admin Portal</h1>
<p>Total uploaded images: <strong>{images.length}</strong></p>
<p>Total uploaded images: <strong>{count}</strong></p>
{error && <p style={{ color: 'crimson' }}>{error}</p>}
<label
style={{
display: 'inline-block',
@@ -91,9 +110,9 @@ export default function AdminPage() {
gap: '1rem',
}}
>
{images.map((src, i) => (
{images.map((img) => (
<div
key={i}
key={img.id}
style={{
border: '1px solid #ddd',
borderRadius: '8px',
@@ -103,12 +122,12 @@ export default function AdminPage() {
}}
>
<img
src={src}
alt={`Uploaded preview ${i + 1}`}
src={img.data}
alt={img.filename}
style={{ width: '100%', height: '160px', objectFit: 'cover' }}
/>
<button
onClick={() => handleDelete(i)}
onClick={() => handleDelete(img.id)}
style={{
padding: '0.5rem',
background: 'crimson',
+63
View File
@@ -0,0 +1,63 @@
import { NextRequest, NextResponse } from 'next/server';
import { requireRole } from '@/lib/auth';
import { db } from '@/lib/db';
export async function GET() {
try {
await requireRole('admin');
const { rows } = await db.query('SELECT id, filename, uploaded_at FROM images ORDER BY uploaded_at DESC');
return NextResponse.json({ images: rows, count: rows.length });
} catch (error) {
if ((error as Error).message === 'Unauthorized') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
console.error('List images error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function POST(request: NextRequest) {
try {
await requireRole('admin');
const body = await request.json();
const { filename, data } = body;
if (!filename || !data) {
return NextResponse.json({ error: 'Missing filename or data' }, { status: 400 });
}
const { rows } = await db.query(
'INSERT INTO images (filename, data) VALUES ($1, $2) RETURNING id, filename, uploaded_at',
[filename, data]
);
return NextResponse.json({ image: rows[0] });
} catch (error) {
if ((error as Error).message === 'Unauthorized') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
console.error('Upload image error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function DELETE(request: NextRequest) {
try {
await requireRole('admin');
const { searchParams } = new URL(request.url);
const id = searchParams.get('id');
if (!id) {
return NextResponse.json({ error: 'Missing id' }, { status: 400 });
}
await db.query('DELETE FROM images WHERE id = $1', [id]);
return NextResponse.json({ ok: true });
} catch (error) {
if ((error as Error).message === 'Unauthorized') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
console.error('Delete image error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+25
View File
@@ -0,0 +1,25 @@
import { NextRequest, NextResponse } from 'next/server';
import { authenticateUser, createSession } from '@/lib/auth';
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { username, password } = body;
if (!username || !password) {
return NextResponse.json({ error: 'Missing username or password' }, { status: 400 });
}
const user = await authenticateUser(username, password);
if (!user) {
return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
}
await createSession(user);
return NextResponse.json({ role: user.role, username: user.username });
} catch (error) {
console.error('Login error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+7
View File
@@ -0,0 +1,7 @@
import { NextResponse } from 'next/server';
import { clearSession } from '@/lib/auth';
export async function POST() {
await clearSession();
return NextResponse.json({ ok: true });
}
+10
View File
@@ -0,0 +1,10 @@
import { NextResponse } from 'next/server';
import { getSession } from '@/lib/auth';
export async function GET() {
const session = await getSession();
if (!session) {
return NextResponse.json({ authenticated: false }, { status: 401 });
}
return NextResponse.json({ authenticated: true, role: session.role, username: session.username });
}
+21
View File
@@ -0,0 +1,21 @@
import { NextResponse } from 'next/server';
import { initSchema, seed, resetDatabase } from '@/lib/schema';
export async function POST(request: Request) {
try {
const { searchParams } = new URL(request.url);
const reset = searchParams.get('reset') === 'true';
if (reset) {
await resetDatabase();
return NextResponse.json({ ok: true, reset: true });
}
await initSchema();
await seed();
return NextResponse.json({ ok: true });
} catch (error) {
console.error('DB init error:', error);
return NextResponse.json({ error: 'Database initialization failed' }, { status: 500 });
}
}
+47
View File
@@ -0,0 +1,47 @@
import { NextResponse } from 'next/server';
import { requireRole } from '@/lib/auth';
import { db } from '@/lib/db';
export async function GET() {
try {
const session = await requireRole('user');
const userId = session.id;
const { rows: reservations } = await db.query(
'SELECT id, date, time, guests, table_name FROM reservations WHERE user_id = $1 ORDER BY date, time',
[userId]
);
const { rows: coupons } = await db.query(
'SELECT id, code, discount FROM coupons WHERE user_id = $1 ORDER BY created_at',
[userId]
);
const { rows: offers } = await db.query(
'SELECT id, title, description FROM offers WHERE active = TRUE ORDER BY created_at'
);
const { rows: benefits } = await db.query(
'SELECT id, text FROM benefits ORDER BY id'
);
const { rows: configRows } = await db.query(
"SELECT value FROM config WHERE key = 'wifi_password'"
);
const wifiPassword = configRows[0]?.value || '';
return NextResponse.json({
reservations,
coupons,
offers,
benefits: benefits.map((b: { text: string }) => b.text),
wifiPassword,
});
} catch (error) {
if ((error as Error).message === 'Unauthorized') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
console.error('User portal error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+8
View File
@@ -0,0 +1,8 @@
export default function CoffeePage() {
return (
<main style={{ padding: '2rem' }}>
<h1>Coffee</h1>
<p>Enjoy locally sourced coffee and fresh pastries.</p>
</main>
);
}
+8
View File
@@ -0,0 +1,8 @@
export default function CommentsPage() {
return (
<main style={{ padding: '2rem' }}>
<h1>Comments</h1>
<p>Read what guests are saying about their stay.</p>
</main>
);
}
+8
View File
@@ -0,0 +1,8 @@
export default function LandscapePage() {
return (
<main style={{ padding: '2rem' }}>
<h1>Landscape</h1>
<p>Explore the trails, rivers, and cloud forest around La Huasca.</p>
</main>
);
}
+7 -2
View File
@@ -1,6 +1,8 @@
import Navbar from '@/components/Navbar';
export const metadata = {
title: 'La Huasca',
description: 'TypeScript + Next.js scaffold with Pretext text measurement',
description: 'TypeScript + Next.js version of La Huasca',
};
export default function RootLayout({
@@ -10,7 +12,10 @@ export default function RootLayout({
}) {
return (
<html lang="en">
<body>{children}</body>
<body style={{ margin: 0, fontFamily: 'system-ui, sans-serif' }}>
<Navbar />
{children}
</body>
</html>
);
}
+16 -8
View File
@@ -2,24 +2,32 @@
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/hooks/useAuth';
export default function LoginPage() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState<string | null>(null);
const { login } = useAuth();
const router = useRouter();
const handleSubmit = (e: React.FormEvent) => {
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);
const ok = login(username, password);
if (ok) {
router.push(username === 'admin' ? '/admin' : '/user');
} else {
setError('Invalid username or password.');
const res = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
credentials: 'same-origin',
});
if (!res.ok) {
const data = await res.json();
setError(data.error || 'Invalid username or password.');
return;
}
const data = await res.json();
router.push(data.role === 'admin' ? '/admin' : '/user');
};
return (
+3 -3
View File
@@ -1,10 +1,10 @@
import MeasuredText from '@/components/MeasuredText';
export default function Home() {
export default function HomePage() {
return (
<main style={{ padding: '2rem', fontFamily: 'system-ui, sans-serif' }}>
<main style={{ padding: '2rem' }}>
<h1>La Huasca</h1>
<p>TypeScript + Next.js scaffold with Pretext text measurement.</p>
<p>Welcome to the TypeScript + Next.js version of La Huasca.</p>
<MeasuredText text="Hello, Pretext!" />
</main>
);
+8
View File
@@ -0,0 +1,8 @@
export default function RoomsPage() {
return (
<main style={{ padding: '2rem' }}>
<h1>Rooms</h1>
<p>Discover our comfortable rooms with stunning views.</p>
</main>
);
}
+56 -42
View File
@@ -1,48 +1,62 @@
'use client';
import { useEffect } from 'react';
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/hooks/useAuth';
const reservations = [
{ id: 1, date: '2026-07-12', time: '19:00', guests: 4, table: 'Terrace 3' },
{ id: 2, date: '2026-07-25', time: '20:30', guests: 2, table: 'Barrel 7' },
];
interface Reservation {
id: number;
date: string;
time: string;
guests: number;
table_name: string;
}
const coupons = [
{ code: 'WELCOME20', discount: '20% off your next stay' },
{ code: 'COFFEE5', discount: '$5 off any coffee tasting' },
];
interface Coupon {
id: number;
code: string;
discount: string;
}
const offers = [
{ title: 'Summer Wine Weekend', desc: 'Complimentary wine tasting with every two-night stay.' },
{ title: 'Sunset Dinner', desc: 'Three-course menu on the terrace every Friday.' },
];
interface Offer {
id: number;
title: string;
description: string;
}
const benefits = [
'Priority booking for peak weekends',
'Late checkout on availability',
'Free welcome cocktail',
'Member-only events and tastings',
];
interface PortalData {
reservations: Reservation[];
coupons: Coupon[];
offers: Offer[];
benefits: string[];
wifiPassword: string;
}
export default function UserPage() {
const { isUser, hydrated } = useAuth();
const router = useRouter();
const [data, setData] = useState<PortalData | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
if (!hydrated) return;
if (!isUser) {
router.push('/login');
}
}, [isUser, hydrated, router]);
fetch('/api/user/portal', { credentials: 'same-origin' })
.then(async (res) => {
if (!res.ok) {
if (res.status === 401) {
router.push('/login');
return;
}
throw new Error('Failed to load portal data');
}
return res.json();
})
.then((json) => setData(json))
.catch((err) => console.error(err))
.finally(() => setLoading(false));
}, [router]);
if (!hydrated || !isUser) {
return (
<main style={{ padding: '2rem' }}>
<p>Please log in as user to access this page.</p>
</main>
);
if (loading) return <main style={{ padding: '2rem' }}><p>Loading...</p></main>;
if (!data) {
return <main style={{ padding: '2rem' }}><p>Please log in as user to access this page.</p></main>;
}
return (
@@ -51,11 +65,11 @@ export default function UserPage() {
<section style={{ marginBottom: '2rem' }}>
<h2>Future Reservations</h2>
{reservations.length === 0 ? (
{data.reservations.length === 0 ? (
<p style={{ color: 'dimgray' }}>No upcoming reservations.</p>
) : (
<ul style={{ padding: 0, listStyle: 'none' }}>
{reservations.map((r) => (
{data.reservations.map((r) => (
<li
key={r.id}
style={{
@@ -65,7 +79,7 @@ export default function UserPage() {
borderRadius: '8px',
}}
>
{r.date} at {r.time} &middot; {r.guests} guests &middot; {r.table}
{r.date} at {r.time} · {r.guests} guests · {r.table_name}
</li>
))}
</ul>
@@ -75,9 +89,9 @@ export default function UserPage() {
<section style={{ marginBottom: '2rem' }}>
<h2>Discount Coupons</h2>
<div style={{ display: 'flex', gap: '1rem', flexWrap: 'wrap' }}>
{coupons.map((c) => (
{data.coupons.map((c) => (
<div
key={c.code}
key={c.id}
style={{
padding: '1rem',
border: '2px dashed #1a1a1a',
@@ -95,9 +109,9 @@ export default function UserPage() {
<section style={{ marginBottom: '2rem' }}>
<h2>Offers</h2>
<ul>
{offers.map((o) => (
<li key={o.title}>
<strong>{o.title}</strong> {o.desc}
{data.offers.map((o) => (
<li key={o.id}>
<strong>{o.title}</strong> {o.description}
</li>
))}
</ul>
@@ -115,14 +129,14 @@ export default function UserPage() {
fontSize: '1.25rem',
}}
>
LaHuascaGuest2026
{data.wifiPassword}
</p>
</section>
<section>
<h2>Member Benefits</h2>
<ul>
{benefits.map((b) => (
{data.benefits.map((b) => (
<li key={b}>{b}</li>
))}
</ul>
+8 -12
View File
@@ -1,7 +1,7 @@
'use client';
import { useEffect, useRef, useState } from 'react';
import { measureText } from '@chenglou/pretext';
import { prepare, layout } from '@chenglou/pretext';
interface MeasuredTextProps {
text: string;
@@ -9,21 +9,17 @@ interface MeasuredTextProps {
export default function MeasuredText({ text }: MeasuredTextProps) {
const ref = useRef<HTMLSpanElement>(null);
const [width, setWidth] = useState<number | null>(null);
const [height, setHeight] = useState<number | null>(null);
useEffect(() => {
if (!ref.current) return;
const style = window.getComputedStyle(ref.current);
const measured = measureText(text, {
font: {
family: style.fontFamily.split(',')[0].replace(/['"]/g, ''),
size: parseFloat(style.fontSize),
weight: style.fontWeight,
},
});
const font = `${style.fontWeight} ${style.fontSize} ${style.fontFamily.split(',')[0].replace(/['"]/g, '')}`;
const prepared = prepare(text, font);
const { height } = layout(prepared, ref.current.offsetWidth, parseFloat(style.lineHeight) || parseFloat(style.fontSize) * 1.2);
setWidth(measured.width);
setHeight(height);
}, [text]);
return (
@@ -31,8 +27,8 @@ export default function MeasuredText({ text }: MeasuredTextProps) {
<span ref={ref} style={{ fontSize: '2rem', fontWeight: 700 }}>
{text}
</span>
{width !== null && (
<p style={{ color: 'dimgray' }}>Measured width: {width.toFixed(2)}px</p>
{height !== null && (
<p style={{ color: 'dimgray' }}>Measured height: {height.toFixed(2)}px</p>
)}
</div>
);
+13 -5
View File
@@ -2,7 +2,7 @@
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/hooks/useAuth';
import { useEffect, useState } from 'react';
const links = [
{ href: '/', label: 'Home' },
@@ -13,11 +13,19 @@ const links = [
];
export default function Navbar() {
const { isLoggedIn, logout } = useAuth();
const [auth, setAuth] = useState<{ authenticated: boolean; role?: string } | null>(null);
const router = useRouter();
const handleLogout = () => {
logout();
useEffect(() => {
fetch('/api/auth/me', { credentials: 'same-origin' })
.then((res) => (res.ok ? res.json() : { authenticated: false }))
.then((data) => setAuth(data))
.catch(() => setAuth({ authenticated: false }));
}, []);
const handleLogout = async () => {
await fetch('/api/auth/logout', { method: 'POST', credentials: 'same-origin' });
setAuth({ authenticated: false });
router.push('/login');
};
@@ -47,7 +55,7 @@ export default function Navbar() {
{link.label}
</Link>
))}
{isLoggedIn ? (
{auth?.authenticated ? (
<button
onClick={handleLogout}
style={{
+64
View File
@@ -0,0 +1,64 @@
import { cookies } from 'next/headers';
import { SignJWT, jwtVerify } from 'jose';
import bcrypt from 'bcryptjs';
import { db } from './db';
const JWT_SECRET = process.env.JWT_SECRET || 'change-me-in-production';
const secret = new TextEncoder().encode(JWT_SECRET);
export async function hashPassword(password: string) {
return bcrypt.hashSync(password, 10);
}
export async function verifyPassword(password: string, hash: string) {
return bcrypt.compareSync(password, hash);
}
export async function authenticateUser(username: string, password: string) {
const { rows } = await db.query('SELECT id, username, password_hash, role FROM users WHERE username = $1', [username]);
if (rows.length === 0) return null;
const user = rows[0];
const valid = await verifyPassword(password, user.password_hash);
if (!valid) return null;
return { id: user.id, username: user.username, role: user.role };
}
export async function createSession(user: { id: number; username: string; role: string }) {
const token = await new SignJWT({ id: user.id, username: user.username, role: user.role })
.setProtectedHeader({ alg: 'HS256' })
.setExpirationTime('7d')
.sign(secret);
cookies().set('session', token, { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax', maxAge: 60 * 60 * 24 * 7 });
return token;
}
export async function getSession() {
const token = cookies().get('session')?.value;
if (!token) return null;
try {
const { payload } = await jwtVerify(token, secret);
return payload as { id: number; username: string; role: string };
} catch {
return null;
}
}
export async function clearSession() {
cookies().delete('session');
}
export async function requireRole(role: 'admin' | 'user') {
const session = await getSession();
if (!session || session.role !== role) {
throw new Error('Unauthorized');
}
return session;
}
export async function requireAuth() {
const session = await getSession();
if (!session) {
throw new Error('Unauthorized');
}
return session;
}
+14
View File
@@ -0,0 +1,14 @@
import { Pool } from 'pg';
const connectionString = process.env.DATABASE_URL;
if (!connectionString) {
throw new Error('DATABASE_URL environment variable is not set');
}
export const db = new Pool({ connectionString });
export async function query(text: string, params?: unknown[]) {
const result = await db.query(text, params);
return result;
}
+151
View File
@@ -0,0 +1,151 @@
import { db } from './db';
import bcrypt from 'bcryptjs';
export async function initSchema() {
await db.query(`
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
password_hash VARCHAR(255) NOT NULL,
role VARCHAR(20) NOT NULL CHECK (role IN ('admin', 'user')),
created_at TIMESTAMP DEFAULT NOW()
);
`);
await db.query(`
CREATE TABLE IF NOT EXISTS images (
id SERIAL PRIMARY KEY,
filename VARCHAR(255) NOT NULL,
data TEXT NOT NULL,
uploaded_at TIMESTAMP DEFAULT NOW()
);
`);
await db.query(`
CREATE TABLE IF NOT EXISTS reservations (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
date DATE NOT NULL,
time TIME NOT NULL,
guests INTEGER NOT NULL,
table_name VARCHAR(100) NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
`);
await db.query(`
CREATE TABLE IF NOT EXISTS coupons (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
code VARCHAR(50) NOT NULL,
discount VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
`);
await db.query(`
CREATE TABLE IF NOT EXISTS offers (
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
description TEXT NOT NULL,
active BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP DEFAULT NOW()
);
`);
await db.query(`
CREATE TABLE IF NOT EXISTS benefits (
id SERIAL PRIMARY KEY,
text VARCHAR(500) NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
`);
await db.query(`
CREATE TABLE IF NOT EXISTS config (
key VARCHAR(100) PRIMARY KEY,
value TEXT NOT NULL
);
`);
}
export async function seed() {
const { rows: adminRows } = await db.query(`SELECT id FROM users WHERE username = 'admin'`);
if (adminRows.length === 0) {
const adminHash = bcrypt.hashSync('admin', 10);
const userHash = bcrypt.hashSync('user', 10);
await db.query(
`INSERT INTO users (username, password_hash, role) VALUES ($1, $2, $3), ($4, $5, $6)`,
['admin', adminHash, 'admin', 'user', userHash, 'user']
);
}
const { rows: offerRows } = await db.query(`SELECT id FROM offers`);
if (offerRows.length === 0) {
await db.query(
`INSERT INTO offers (title, description) VALUES
($1, $2), ($3, $4)`,
[
'Summer Wine Weekend', 'Complimentary wine tasting with every two-night stay.',
'Sunset Dinner', 'Three-course menu on the terrace every Friday.',
]
);
}
const { rows: benefitRows } = await db.query(`SELECT id FROM benefits`);
if (benefitRows.length === 0) {
await db.query(
`INSERT INTO benefits (text) VALUES
($1), ($2), ($3), ($4)`,
[
'Priority booking for peak weekends',
'Late checkout on availability',
'Free welcome cocktail',
'Member-only events and tastings',
]
);
}
const { rows: configRows } = await db.query(`SELECT key FROM config WHERE key = 'wifi_password'`);
if (configRows.length === 0) {
await db.query(
`INSERT INTO config (key, value) VALUES ($1, $2)`,
['wifi_password', 'LaHuascaGuest2026']
);
}
const { rows: userResRows } = await db.query(`SELECT id FROM reservations WHERE user_id = (SELECT id FROM users WHERE username = 'user')`);
if (userResRows.length === 0) {
await db.query(
`INSERT INTO reservations (user_id, date, time, guests, table_name)
SELECT id, $2, $3, $4, $5 FROM users WHERE username = $1`,
['user', '2026-07-12', '19:00', 4, 'Terrace 3']
);
await db.query(
`INSERT INTO reservations (user_id, date, time, guests, table_name)
SELECT id, $2, $3, $4, $5 FROM users WHERE username = $1`,
['user', '2026-07-25', '20:30', 2, 'Barrel 7']
);
}
const { rows: userCouponRows } = await db.query(`SELECT id FROM coupons WHERE user_id = (SELECT id FROM users WHERE username = 'user')`);
if (userCouponRows.length === 0) {
await db.query(
`INSERT INTO coupons (user_id, code, discount)
SELECT id, $2, $3 FROM users WHERE username = $1`,
['user', 'WELCOME20', '20% off your next stay']
);
await db.query(
`INSERT INTO coupons (user_id, code, discount)
SELECT id, $2, $3 FROM users WHERE username = $1`,
['user', 'COFFEE5', '$5 off any coffee tasting']
);
}
}
export async function resetDatabase() {
await db.query('DROP TABLE IF EXISTS config, benefits, offers, coupons, reservations, images, users CASCADE');
await initSchema();
await seed();
}