import { Router, Request, Response } from 'express';
import { Op, fn, col } from 'sequelize';
import Rental from '../models/mysql/Rental';

const router = Router();

// GET /api/locations — شهرها و تعداد آگهی هر شهر
router.get('/', async (_req: Request, res: Response) => {
    try {
        const cities = await Rental.findAll({
            attributes: [
                'city_name',
                [fn('COUNT', col('id')), 'count'],
            ],
            where: { city_name: { [Op.not]: null } },
            group: ['city_name'],
            order: [[fn('COUNT', col('id')), 'DESC']],
            raw: true,
        });

        res.json({
            success: true,
            data: cities.filter((c: any) => c.city_name),
        });
    } catch (error) {
        console.error('Error fetching locations:', error);
        res.status(500).json({ success: false, message: 'خطا در دریافت لوکیشن‌ها' });
    }
});

export default router;
