const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const { Pool } = require('pg');
const multer = require('multer');
const path = require('path');
const fs = require('fs');

dotenv.config();

const app = express();
const PORT = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

const uploadsDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadsDir)) fs.mkdirSync(uploadsDir);

app.use('/uploads', express.static(uploadsDir));

const pool = new Pool({
    user: process.env.DB_USER || 'postgres',
    host: process.env.DB_HOST || '127.0.0.1',
    database: process.env.DB_NAME || 'car',
    password: process.env.DB_PASSWORD,
    port: parseInt(process.env.DB_PORT) || 5432,
});

// Test DB connection on startup
pool.connect((err, client, release) => {
    if (err) {
        console.error('\n❌ DATABASE CONNECTION FAILED!');
        console.error('   Error:', err.message);
        console.error('   Make sure PostgreSQL is running on port', process.env.DB_PORT || 5432);
        console.error('   DB:', process.env.DB_NAME, '| User:', process.env.DB_USER, '| Host:', process.env.DB_HOST);
    } else {
        console.log('✅ Database connected successfully!');
        release();
    }
});

const storage = multer.diskStorage({
    destination: (req, file, cb) => cb(null, uploadsDir),
    filename: (req, file, cb) => {
        const uniqueName = `car_${Date.now()}${path.extname(file.originalname)}`;
        cb(null, uniqueName);
    }
});
const upload = multer({
  storage,
  limits: { fileSize: 10 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    if (
      file.mimetype.startsWith('image/') ||
      file.mimetype.startsWith('video/')
    ) {
      cb(null, true);
    } else {
      cb(new Error("Only images or videos allowed"));
    }
  }
});

// Image upload endpoint
app.post('/api/upload', upload.single('image'), (req, res) => {
    if (!req.file) return res.status(400).json({ message: 'No file uploaded' });
    const imageUrl = `http://127.0.0.1:${PORT}/uploads/${req.file.filename}`;
    res.json({ url: imageUrl, filename: req.file.filename });
});

app.get('/', (req, res) => {
    res.send('Car Rental Admin API is running...');
});

// Routes
app.use('/api/auth', require('./routes/auth'));
app.use('/api/cars', require('./routes/cars'));
app.use('/api/bookings', require('./routes/bookings'));

const customerRoutes = require('./routes/customer');
app.use('/api/customers', customerRoutes);
app.listen(PORT, '127.0.0.1', () => {
    console.log(`Server is running on http://127.0.0.1:${PORT}`);
});
