import express, { Request, Response, NextFunction } from 'express';
import { fetchFromDivar } from './bots/divar';
import sequelize from './config/sequelize';
import dotenv from 'dotenv';
import cron from 'node-cron';
import rentalsRouter from './routes/rentals';
import locationsRouter from './routes/locations';
import './models/mysql/RentalImage'; // اطمینان از لود شدن association

dotenv.config();

const app = express();
const PORT = process.env.PORT || 3000;
const FRONTEND_URL = process.env.FRONTEND_URL || '*';

app.use(express.json());

// CORS
app.use((req: Request, res: Response, next: NextFunction) => {
    res.setHeader('Access-Control-Allow-Origin', FRONTEND_URL);
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    if (req.method === 'OPTIONS') {
        res.sendStatus(204);
        return;
    }
    next();
});

// Routes
app.use('/api/rentals', rentalsRouter);
app.use('/api/locations', locationsRouter);

// Health check
app.get('/health', (_req, res) => {
    res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

async function start() {
    try {
        await sequelize.authenticate();
        await sequelize.sync();
        console.log('✅ MySQL connected');

        cron.schedule('*/30 * * * *', () => {
            console.log('🕒 Running Divar scrape job');
            fetchFromDivar();
        });

        app.listen(PORT, () => {
            console.log(`🚀 Server running on port ${PORT}`);
            fetchFromDivar();
        });
    } catch (error) {
        console.error('Failed to start server:', error);
    }
}

start();
