import { Router, Response } from 'express';
import { requireAuth, requireAdmin, AuthRequest } from '../../middleware/auth.middleware';
import { AdminService } from '../../services/admin.service';
import { ShopService } from '../../services/shop.service';
import { ShopProductCategory, ShopProductStatus } from '../../models/ShopProduct';

const router = Router();

// All admin routes require authentication + admin role
router.use(requireAuth);
router.use(requireAdmin);

// ─── Dashboard ──────────────────────────────────────────────

router.get('/stats', async (_req: AuthRequest, res: Response) => {
  try {
    const stats = await AdminService.getDashboardStats();
    res.json(stats);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.get('/activity', async (req: AuthRequest, res: Response) => {
  try {
    const limit = parseInt(req.query.limit as string) || 20;
    const activity = await AdminService.getRecentActivity(limit);
    res.json(activity);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

// ─── Players ────────────────────────────────────────────────

router.get('/players', async (req: AuthRequest, res: Response) => {
  try {
    const { search, role, status } = req.query;
    const page = parseInt(req.query.page as string) || 1;
    const limit = parseInt(req.query.limit as string) || 20;

    const result = await AdminService.getPlayers(
      search as string,
      role as string,
      status as string,
      page,
      limit,
    );
    res.json(result);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.get('/players/:id', async (req: AuthRequest, res: Response) => {
  try {
    const player = await AdminService.getPlayerDetail(req.params.id);
    if (!player) {
      res.status(404).json({ error: 'Joueur introuvable' });
      return;
    }
    res.json(player);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.put('/players/:id/role', async (req: AuthRequest, res: Response) => {
  try {
    const { role } = req.body;
    if (!['player', 'moderator', 'admin'].includes(role)) {
      res.status(400).json({ error: 'Rôle invalide. Valeurs acceptées: player, moderator, admin' });
      return;
    }
    const result = await AdminService.updatePlayerRole(req.params.id, role);
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

router.post('/players/:id/ban', async (req: AuthRequest, res: Response) => {
  try {
    const { reason, duration } = req.body;
    if (!reason) {
      res.status(400).json({ error: 'La raison du bannissement est requise' });
      return;
    }
    const result = await AdminService.banPlayer(
      req.params.id,
      reason,
      duration || 0,
      req.playerId!,
    );
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

router.post('/players/:id/unban', async (req: AuthRequest, res: Response) => {
  try {
    const result = await AdminService.unbanPlayer(req.params.id);
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

// Phase 16 (2026-04-22) — reset password déclenché par un admin.
// Délègue à AuthService.requestPasswordReset (envoie le mail avec token 1h).
router.post('/players/:id/reset-password', async (req: AuthRequest, res: Response) => {
  try {
    const { AppDataSource } = await import('../../config/database');
    const { Player } = await import('../../models/Player');
    const player = await AppDataSource.getRepository(Player).findOneBy({ id: req.params.id });
    if (!player) return res.status(404).json({ error: 'Joueur introuvable' });
    if (!player.email) return res.status(400).json({ error: 'Joueur sans email — reset impossible' });

    const { AuthService } = await import('../../services/auth.service');
    await AuthService.requestPasswordReset(player.email);

    res.json({ success: true, email: player.email });
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/players/:id/balance', async (req: AuthRequest, res: Response) => {
  try {
    const { currency, amount } = req.body;
    const validCurrencies = ['infinite_light', 'infinite_shadow', 'dagaz', 'quintessence'];
    if (!validCurrencies.includes(currency)) {
      res.status(400).json({ error: `Devise invalide. Valeurs acceptées: ${validCurrencies.join(', ')}` });
      return;
    }
    if (typeof amount !== 'number') {
      res.status(400).json({ error: 'Le montant doit être un nombre' });
      return;
    }
    const result = await AdminService.adjustPlayerBalance(req.params.id, currency, amount);
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

// ─── Blog ───────────────────────────────────────────────────

router.get('/blog', async (req: AuthRequest, res: Response) => {
  try {
    const { search, category, status } = req.query;
    const articles = await AdminService.getBlogArticles(
      search as string,
      category as string,
      status as string,
    );
    res.json(articles);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/blog', async (req: AuthRequest, res: Response) => {
  try {
    const { title, content, excerpt, cover_image_url, category, status, slug } = req.body;
    if (!title || !content || !slug) {
      res.status(400).json({ error: 'title, content et slug sont requis' });
      return;
    }
    const article = await AdminService.createBlogArticle({
      author_id: req.playerId!,
      title,
      content,
      excerpt,
      cover_image_url,
      category,
      status,
      slug,
    });
    res.status(201).json(article);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

router.put('/blog/:id', async (req: AuthRequest, res: Response) => {
  try {
    const article = await AdminService.updateBlogArticle(req.params.id, req.body);
    res.json(article);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

router.delete('/blog/:id', async (req: AuthRequest, res: Response) => {
  try {
    const result = await AdminService.deleteBlogArticle(req.params.id);
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

// ─── Forum Moderation ───────────────────────────────────────

router.get('/forum/moderation', async (_req: AuthRequest, res: Response) => {
  try {
    const queue = await AdminService.getForumModerationQueue();
    res.json(queue);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/forum/moderation/:id/approve', async (req: AuthRequest, res: Response) => {
  try {
    const { type } = req.body;
    if (!type || !['discussion', 'reply'].includes(type)) {
      res.status(400).json({ error: 'Type requis: discussion ou reply' });
      return;
    }
    const result = await AdminService.approveForumItem(req.params.id, type);
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

router.post('/forum/moderation/:id/reject', async (req: AuthRequest, res: Response) => {
  try {
    const { type } = req.body;
    if (!type || !['discussion', 'reply'].includes(type)) {
      res.status(400).json({ error: 'Type requis: discussion ou reply' });
      return;
    }
    const result = await AdminService.rejectForumItem(req.params.id, type);
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

// ─── Forum Categories ───────────────────────────────────────

router.get('/forum/categories', async (_req: AuthRequest, res: Response) => {
  try {
    const categories = await AdminService.getForumCategories();
    res.json(categories);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/forum/categories', async (req: AuthRequest, res: Response) => {
  try {
    const { name, description, icon, sort_order, members_only } = req.body;
    if (!name) {
      res.status(400).json({ error: 'Le nom de la catégorie est requis' });
      return;
    }
    const category = await AdminService.createForumCategory({
      name,
      description,
      icon,
      sort_order,
      members_only,
    });
    res.status(201).json(category);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

router.put('/forum/categories/:id', async (req: AuthRequest, res: Response) => {
  try {
    const category = await AdminService.updateForumCategory(req.params.id, req.body);
    res.json(category);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

router.delete('/forum/categories/:id', async (req: AuthRequest, res: Response) => {
  try {
    const result = await AdminService.deleteForumCategory(req.params.id);
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

// ─── Shop ────────────────────────────────────────────────────

router.get('/shop/products', async (req: AuthRequest, res: Response) => {
  try {
    const { category, search, status } = req.query;
    const page = parseInt(req.query.page as string) || 1;
    const limit = parseInt(req.query.limit as string) || 20;

    const result = await ShopService.getAllProducts(
      category as string,
      search as string,
      status as string,
      page,
      limit,
    );
    res.json(result);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.get('/shop/stats', async (_req: AuthRequest, res: Response) => {
  try {
    const stats = await ShopService.getStats();
    res.json(stats);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/shop/products', async (req: AuthRequest, res: Response) => {
  try {
    const { name, description, price, category, stock, image_url, status } = req.body;

    if (!name || !description || price === undefined || !category) {
      res.status(400).json({ error: 'name, description, price et category sont requis' });
      return;
    }

    const validCategories: ShopProductCategory[] = ['armes', 'vehicules', 'vetements', 'consommables', 'special'];
    if (!validCategories.includes(category)) {
      res.status(400).json({ error: `Catégorie invalide. Valeurs acceptées: ${validCategories.join(', ')}` });
      return;
    }

    if (typeof price !== 'number' || price < 0) {
      res.status(400).json({ error: 'Le prix doit être un nombre positif' });
      return;
    }

    const product = await ShopService.createProduct({
      name,
      description,
      price,
      category,
      stock,
      image_url,
      status,
    });
    res.status(201).json(product);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

router.put('/shop/products/:id', async (req: AuthRequest, res: Response) => {
  try {
    const { category, status, price } = req.body;

    const validCategories: ShopProductCategory[] = ['armes', 'vehicules', 'vetements', 'consommables', 'special'];
    if (category !== undefined && !validCategories.includes(category)) {
      res.status(400).json({ error: `Catégorie invalide. Valeurs acceptées: ${validCategories.join(', ')}` });
      return;
    }

    const validStatuses: ShopProductStatus[] = ['en_vente', 'epuise', 'desactive'];
    if (status !== undefined && !validStatuses.includes(status)) {
      res.status(400).json({ error: `Statut invalide. Valeurs acceptées: ${validStatuses.join(', ')}` });
      return;
    }

    if (price !== undefined && (typeof price !== 'number' || price < 0)) {
      res.status(400).json({ error: 'Le prix doit être un nombre positif' });
      return;
    }

    const product = await ShopService.updateProduct(req.params.id, req.body);
    res.json(product);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

router.delete('/shop/products/:id', async (req: AuthRequest, res: Response) => {
  try {
    const result = await ShopService.deleteProduct(req.params.id);
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

// ─── Newsletter ─────────────────────────────────────────────

router.get('/newsletter/history', async (_req: AuthRequest, res: Response) => {
  try {
    const history = await AdminService.getNewsletterHistory();
    res.json(history);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.get('/newsletter/subscribers', async (_req: AuthRequest, res: Response) => {
  try {
    const result = await AdminService.getNewsletterSubscriberCount();
    res.json(result);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

// ─── Moderation — Reports ────────────────────────────────

router.get('/moderation/reports', async (req: AuthRequest, res: Response) => {
  try {
    const { status } = req.query;
    const reports = await AdminService.getReports(status as string);
    res.json(reports);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/moderation/reports/:id/dismiss', async (req: AuthRequest, res: Response) => {
  try {
    const result = await AdminService.dismissReport(req.params.id, req.playerId!);
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

router.post('/moderation/reports/:id/sanction', async (req: AuthRequest, res: Response) => {
  try {
    const { type, reason, duration, expires_at } = req.body;
    if (!type || !['ban', 'suspension', 'mute'].includes(type)) {
      res.status(400).json({ error: 'Type de sanction invalide. Valeurs acceptées: ban, suspension, mute' });
      return;
    }
    if (!reason) {
      res.status(400).json({ error: 'La raison de la sanction est requise' });
      return;
    }
    if (!duration) {
      res.status(400).json({ error: 'La durée de la sanction est requise' });
      return;
    }
    const result = await AdminService.sanctionFromReport(
      req.params.id,
      { type, reason, duration, expires_at: expires_at || null },
      req.playerId!,
    );
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

router.post('/moderation/reports/:id/delete-content', async (req: AuthRequest, res: Response) => {
  try {
    const result = await AdminService.deleteReportContent(req.params.id, req.playerId!);
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

// ─── Moderation — Sanctions ──────────────────────────────

router.get('/moderation/sanctions', async (req: AuthRequest, res: Response) => {
  try {
    const { active } = req.query;
    const sanctions = await AdminService.getSanctions(active as string);
    res.json(sanctions);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.put('/moderation/sanctions/:id/lift', async (req: AuthRequest, res: Response) => {
  try {
    const result = await AdminService.liftSanction(req.params.id, req.playerId!);
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

router.put('/moderation/sanctions/:id/duration', async (req: AuthRequest, res: Response) => {
  try {
    const { duration, expires_at } = req.body;
    if (!duration) {
      res.status(400).json({ error: 'La nouvelle durée est requise' });
      return;
    }
    const result = await AdminService.updateSanctionDuration(
      req.params.id,
      duration,
      expires_at || null,
      req.playerId!,
    );
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

// ─── Moderation — Warnings (Phase 16, 2026-04-22) ────────
// Stockés dans `moderation_logs` avec action='warning:<severity>' + Notification
// au joueur ciblé.

router.get('/moderation/warnings', async (req: AuthRequest, res: Response) => {
  try {
    const limit = Math.min(200, Math.max(1, parseInt(req.query.limit as string) || 50));
    const warnings = await AdminService.listWarnings(limit);
    res.json(warnings);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/moderation/warnings', async (req: AuthRequest, res: Response) => {
  try {
    const { player_username, severity, reason } = req.body;
    if (!player_username || !severity || !reason) {
      return res.status(400).json({ error: 'player_username, severity et reason sont requis' });
    }
    const result = await AdminService.createWarning(
      req.playerId!,
      String(player_username),
      severity as 'low' | 'medium' | 'high',
      String(reason),
    );
    res.status(201).json(result);
  } catch (err: any) {
    const status = err.message.includes('introuvable') ? 404
      : err.message.includes('requise') || err.message.includes('invalide') ? 400
      : 500;
    res.status(status).json({ error: err.message });
  }
});

// ─── Moderation — Logs ───────────────────────────────────

router.get('/moderation/logs', async (req: AuthRequest, res: Response) => {
  try {
    const { moderator, action, dateFrom, dateTo } = req.query;
    const logs = await AdminService.getModerationLogs(
      moderator as string,
      action as string,
      dateFrom as string,
      dateTo as string,
    );
    res.json(logs);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

// ─── World Stock View ────────────────────────────────────────

/** GET /api/admin/world-stock — Global view of all items, production, currencies */
router.get('/world-stock', async (_req: AuthRequest, res: Response) => {
  try {
    const stock = await AdminService.getWorldStock();
    res.json(stock);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

// ─── Game Settings (admin CRUD) ─────────────────────────────

router.get('/settings', async (_req: AuthRequest, res: Response) => {
  try {
    const { AppDataSource } = await import('../../config/database');
    const { GameSetting } = await import('../../models/GameSetting');
    const settings = await AppDataSource.getRepository(GameSetting).find({
      order: { category: 'ASC', key: 'ASC' },
    });
    res.json(settings);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.put('/settings/:id', async (req: AuthRequest, res: Response) => {
  try {
    const { AppDataSource } = await import('../../config/database');
    const { GameSetting } = await import('../../models/GameSetting');
    const repo = AppDataSource.getRepository(GameSetting);
    const setting = await repo.findOne({ where: { id: req.params.id } });
    if (!setting) return res.status(404).json({ error: 'Setting introuvable' });

    const { value, description, category, is_public } = req.body;
    if (value !== undefined) setting.value = typeof value === 'string' ? value : JSON.stringify(value);
    if (description !== undefined) setting.description = description;
    if (category !== undefined) setting.category = category;
    if (is_public !== undefined) setting.is_public = is_public;

    await repo.save(setting);
    res.json(setting);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/settings', async (req: AuthRequest, res: Response) => {
  try {
    const { AppDataSource } = await import('../../config/database');
    const { GameSetting } = await import('../../models/GameSetting');
    const repo = AppDataSource.getRepository(GameSetting);
    const { key, value, description, category, is_public } = req.body;
    if (!key) return res.status(400).json({ error: 'key requis' });

    const setting = repo.create({
      key,
      value: typeof value === 'string' ? value : JSON.stringify(value ?? ''),
      description: description || null,
      category: category || 'general',
      is_public: is_public ?? false,
    });
    await repo.save(setting);
    res.status(201).json(setting);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.delete('/settings/:id', async (req: AuthRequest, res: Response) => {
  try {
    const { AppDataSource } = await import('../../config/database');
    const { GameSetting } = await import('../../models/GameSetting');
    const repo = AppDataSource.getRepository(GameSetting);
    const result = await repo.delete(req.params.id);
    if (result.affected === 0) return res.status(404).json({ error: 'Setting introuvable' });
    res.json({ success: true });
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

// ─── BlackMarket / Drugs (admin CRUD) ──────────────────────

router.get('/blackmarket/drugs', async (_req: AuthRequest, res: Response) => {
  try {
    const { AppDataSource } = await import('../../config/database');
    const { Drug } = await import('../../models/Drug');
    const drugs = await AppDataSource.getRepository(Drug).find({
      order: { sort_order: 'ASC', name: 'ASC' },
    });
    res.json(drugs);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.post('/blackmarket/drugs', async (req: AuthRequest, res: Response) => {
  try {
    const { AppDataSource } = await import('../../config/database');
    const { Drug } = await import('../../models/Drug');
    const repo = AppDataSource.getRepository(Drug);
    const drug = repo.create(req.body);
    await repo.save(drug);
    res.status(201).json(drug);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.put('/blackmarket/drugs/:id', async (req: AuthRequest, res: Response) => {
  try {
    const { AppDataSource } = await import('../../config/database');
    const { Drug } = await import('../../models/Drug');
    const repo = AppDataSource.getRepository(Drug);
    const drug = await repo.findOne({ where: { id: req.params.id } });
    if (!drug) return res.status(404).json({ error: 'Drogue introuvable' });

    Object.assign(drug, req.body);
    await repo.save(drug);
    res.json(drug);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.delete('/blackmarket/drugs/:id', async (req: AuthRequest, res: Response) => {
  try {
    const { AppDataSource } = await import('../../config/database');
    const { Drug } = await import('../../models/Drug');
    const repo = AppDataSource.getRepository(Drug);
    const result = await repo.delete(req.params.id);
    if (result.affected === 0) return res.status(404).json({ error: 'Drogue introuvable' });
    res.json({ success: true });
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});


// ─── Error Reports ──────────────────────────────────────────

router.get('/error-reports', async (req: AuthRequest, res: Response) => {
  try {
    const { AppDataSource } = await import('../../config/database');
    const { ErrorReport } = await import('../../models/ErrorReport');
    const repo = AppDataSource.getRepository(ErrorReport);
    const page = parseInt(req.query.page as string) || 1;
    const limit = Math.min(parseInt(req.query.limit as string) || 50, 200);
    const [reports, total] = await repo.findAndCount({
      order: { created_at: 'DESC' },
      take: limit,
      skip: (page - 1) * limit,
    });
    res.json({ reports, total, page, limit });
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.delete('/error-reports/:id', async (req: AuthRequest, res: Response) => {
  try {
    const { AppDataSource } = await import('../../config/database');
    const { ErrorReport } = await import('../../models/ErrorReport');
    const repo = AppDataSource.getRepository(ErrorReport);
    const result = await repo.delete(req.params.id);
    if (result.affected === 0) return res.status(404).json({ error: 'Report introuvable' });
    res.json({ success: true });
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.delete('/error-reports', async (_req: AuthRequest, res: Response) => {
  try {
    const { AppDataSource } = await import('../../config/database');
    const { ErrorReport } = await import('../../models/ErrorReport');
    await AppDataSource.getRepository(ErrorReport).clear();
    res.json({ success: true });
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

export default router;

