// Example: PostgreSQL Chat Implementation for Railway
// This uses the DATABASE_URL that Railway provides automatically

import { sql } from '@vercel/postgres';
import { NextRequest, NextResponse } from 'next/server';

// GET recent messages
export async function GET(request: NextRequest) {
  try {
    const result = await sql`
      SELECT id, username, message, timestamp 
      FROM messages 
      ORDER BY timestamp DESC 
      LIMIT 100
    `;
    
    return NextResponse.json({
      messages: result.rows.reverse(),
    });
  } catch (error) {
    console.error('Database error:', error);
    return NextResponse.json(
      { error: 'Failed to fetch messages' },
      { status: 500 }
    );
  }
}

// POST new message
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { username, message } = body;

    // Validate
    if (!username || !message) {
      return NextResponse.json(
        { error: 'Username and message required' },
        { status: 400 }
      );
    }

    if (message.length > 500) {
      return NextResponse.json(
        { error: 'Message too long' },
        { status: 400 }
      );
    }

    // Insert into database
    const result = await sql`
      INSERT INTO messages (username, message, timestamp)
      VALUES (${username}, ${message}, NOW())
      RETURNING id, username, message, timestamp
    `;

    return NextResponse.json({
      success: true,
      message: result.rows[0],
    });
  } catch (error) {
    console.error('Database error:', error);
    return NextResponse.json(
      { error: 'Failed to post message' },
      { status: 500 }
    );
  }
}

// You'll need to initialize the database with this schema once:
/*
CREATE TABLE IF NOT EXISTS messages (
  id SERIAL PRIMARY KEY,
  username VARCHAR(255) NOT NULL,
  message TEXT NOT NULL,
  timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX idx_messages_timestamp ON messages(timestamp DESC);
*/

// Setup instructions:
// 1. In Railway dashboard, add PostgreSQL database to your project
// 2. Railway auto-sets DATABASE_URL environment variable
// 3. Run the schema creation query once
// 4. Update your chat component to use this API
