import express from 'express';
import { createServer } from 'http';
import cors from 'cors';
import helmet from 'helmet';
import cookieParser from 'cookie-parser';
import rateLimit from 'express-rate-limit';
import path from 'path';
import { fileURLToPath } from 'url';
import { env } from './config/env.js';
import { errorHandler } from './middleware/errorHandler.js';
import { setupSocket } from './socket/index.js';
import authRoutes from './routes/auth.js';
import userRoutes from './routes/user.js';
import listingRoutes from './routes/listing.js';
import offerRoutes from './routes/offer.js';
import chatRoutes from './routes/chat.js';
import notificationRoutes from './routes/notification.js';
import paymentRoutes from './routes/payment.js';
import locationRoutes from './routes/location.js';
import miscRoutes from './routes/misc.js';
import reportRoutes from './routes/report.js';
import subscriptionRoutes from './routes/subscription.js';
import promotionRoutes from './routes/promotion.js';
import adminRoutes from './routes/admin/index.js';
import rentalRoutes from './routes/rental.js';
import bookingRoutes from './routes/booking.js';
import rentalPaymentRoutes from './routes/rental-payment.js';
import payoutRoutes from './routes/payout.js';
import rentalReviewRoutes from './routes/rental-review.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

const app = express();
const httpServer = createServer(app);

// Socket.io
const io = setupSocket(httpServer);
app.set('io', io);

// Middleware
app.use(helmet({ contentSecurityPolicy: false }));
app.use(cors({ origin: env.CLIENT_URL, credentials: true }));
app.use(cookieParser());

// Stripe webhook needs raw body
app.use('/api/payments/webhook', express.raw({ type: 'application/json' }));
app.use('/api/rental-payments/webhook', express.raw({ type: 'application/json' }));
app.use(express.json());

// Rate limiting
const authLimiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 50 });
app.use('/api/auth/login', authLimiter);
app.use('/api/auth/register', authLimiter);

// Static files
app.use('/uploads', express.static(path.join(__dirname, '..', env.UPLOAD_DIR)));

// Routes
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/listings', listingRoutes);
app.use('/api/offers', offerRoutes);
app.use('/api/chat', chatRoutes);
app.use('/api/notifications', notificationRoutes);
app.use('/api/payments', paymentRoutes);
app.use('/api/location', locationRoutes);
app.use('/api', miscRoutes);
app.use('/api/reports', reportRoutes);
app.use('/api/subscriptions', subscriptionRoutes);
app.use('/api/promotions', promotionRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api/rentals', rentalRoutes);
app.use('/api/bookings', bookingRoutes);
app.use('/api/rental-payments', rentalPaymentRoutes);
app.use('/api/payouts', payoutRoutes);
app.use('/api/rental-reviews', rentalReviewRoutes);

// Health check
app.get('/api/health', (_req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// Error handler
app.use(errorHandler);

httpServer.listen(env.PORT, () => {
  console.log(`Server running on port ${env.PORT}`);
});
