import express from 'express';
import { User, Service } from '../models/index.js';
import { Op } from 'sequelize';
import { auth } from '../middleware/authMiddleware.js';
import multer from 'multer';
import { v4 as uuidv4 } from 'uuid';
import path from 'path';
import bcrypt from 'bcryptjs';

const router = express.Router();

const storage = multer.diskStorage({
  destination: 'uploads/',
  filename: (req, file, cb) => cb(null, `${uuidv4()}${path.extname(file.originalname)}`)
});
const upload = multer({ storage, limits: { fileSize: 5 * 1024 * 1024 } });

router.put('/profile', auth(), upload.single('avatar'), async (req, res) => {
  try {
    const updates = { ...req.body };
    if (req.file) updates.avatar = `/uploads/${req.file.filename}`;
    if (updates.password) {
      updates.password = await bcrypt.hash(updates.password, 12);
    }
    await req.user.update(updates);
    res.json({ user: req.user });
  } catch (e) {
    res.status(500).json({ error: 'Update failed' });
  }
});

router.get('/providers', async (req, res) => {
  try {
    const { category, lat, lng, radius = 10000, page = 1, limit = 10 } = req.query;
    const offset = (page - 1) * limit;
    const where = { role: 'provider', is_verified: true };
    const include = [];

    if (category) {
      include.push({ model: Service, as: 'services', where: { category }, required: true });
    }

    if (lat && lng) {
      where.latitude = { [Op.between]: [parseFloat(lat) - radius / 111000, parseFloat(lat) + radius / 111000] };
      where.longitude = { [Op.between]: [parseFloat(lng) - radius / 111000, parseFloat(lng) + radius / 111000] };
    }

    const { count, rows: providers } = await User.findAndCountAll({
      where, include, offset: parseInt(offset), limit: parseInt(limit),
      attributes: { exclude: ['password'] }, order: [['rating', 'DESC']]
    });
    res.json({ providers, total: count, page: parseInt(page), pages: Math.ceil(count / limit) });
  } catch (e) {
    res.status(500).json({ error: 'Failed to fetch providers' });
  }
});

export default router;