import { MoreThan, Like, In, Between, MoreThanOrEqual, LessThanOrEqual } from 'typeorm';
import { AppDataSource } from '../config/database';
import { Player } from '../models/Player';
import { Report } from '../models/Report';
import { Sanction } from '../models/Sanction';
import { ModerationLog } from '../models/ModerationLog';
import { PlayerBalances } from '../models/PlayerBalances';
import { PlayerAxes } from '../models/PlayerAxes';
import { PlayerSkills } from '../models/PlayerSkills';
import { PlayerGauges } from '../models/PlayerGauges';
import { PlayerHealth } from '../models/PlayerHealth';
import { PlayerInventory } from '../models/PlayerInventory';
import { Discussion } from '../models/Discussion';
import { Reply } from '../models/Reply';
import { BlogPost } from '../models/BlogPost';
import { ForumCategory } from '../models/ForumCategory';
import { Listing } from '../models/Listing';
import { ProductionBatch } from '../models/ProductionBatch';
import { Business } from '../models/Business';

export class AdminService {
  // ─── Dashboard ──────────────────────────────────────────────

  static async getDashboardStats() {
    const playerRepo = AppDataSource.getRepository(Player);
    const discussionRepo = AppDataSource.getRepository(Discussion);
    const blogRepo = AppDataSource.getRepository(BlogPost);
    const listingRepo = AppDataSource.getRepository(Listing);

    const now = new Date();
    const twentyFourHoursAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000);
    const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);

    const [
      totalPlayers,
      activePlayers24h,
      newRegistrations7d,
      totalDiscussions,
      totalBlogPosts,
      totalListings,
      newsletterSubscribers,
    ] = await Promise.all([
      playerRepo.count(),
      playerRepo.count({
        where: { last_login: MoreThan(twentyFourHoursAgo) },
      }),
      playerRepo.count({
        where: { created_at: MoreThan(sevenDaysAgo) },
      }),
      discussionRepo.count(),
      blogRepo.count(),
      listingRepo.count(),
      playerRepo.count({
        where: { newsletter_optin: true },
      }),
    ]);

    return {
      totalPlayers,
      activePlayers24h,
      newRegistrations7d,
      totalDiscussions,
      totalBlogPosts,
      totalListings,
      newsletterSubscribers,
    };
  }

  // ─── Recent Activity ────────────────────────────────────────

  static async getRecentActivity(limit: number = 20) {
    const playerRepo = AppDataSource.getRepository(Player);
    const discussionRepo = AppDataSource.getRepository(Discussion);
    const blogRepo = AppDataSource.getRepository(BlogPost);
    const listingRepo = AppDataSource.getRepository(Listing);

    const [newPlayers, newDiscussions, newBlogPosts, newListings] = await Promise.all([
      playerRepo.find({
        select: ['id', 'username', 'created_at'],
        order: { created_at: 'DESC' },
        take: limit,
      }),
      discussionRepo.find({
        relations: ['author'],
        order: { created_at: 'DESC' },
        take: limit,
      }),
      blogRepo.find({
        relations: ['author'],
        order: { created_at: 'DESC' },
        take: limit,
      }),
      listingRepo.find({
        relations: ['seller'],
        order: { created_at: 'DESC' },
        take: limit,
      }),
    ]);

    // Merge and sort all activity by date
    const activity: Array<{ type: string; data: any; date: Date }> = [];

    for (const p of newPlayers) {
      activity.push({
        type: 'registration',
        data: { id: p.id, username: p.username },
        date: p.created_at,
      });
    }

    for (const d of newDiscussions) {
      activity.push({
        type: 'forum_discussion',
        data: {
          id: d.id,
          title: d.title,
          author: d.author ? { id: d.author.id, username: d.author.username } : null,
        },
        date: d.created_at,
      });
    }

    for (const b of newBlogPosts) {
      activity.push({
        type: 'blog_article',
        data: {
          id: b.id,
          title: b.title,
          author: b.author ? { id: b.author.id, username: b.author.username } : null,
        },
        date: b.created_at,
      });
    }

    for (const l of newListings) {
      activity.push({
        type: 'marketplace_listing',
        data: {
          id: l.id,
          title: l.title,
          seller: l.seller ? { id: l.seller.id, username: l.seller.username } : null,
        },
        date: l.created_at,
      });
    }

    // Sort by date descending and limit
    activity.sort((a, b) => b.date.getTime() - a.date.getTime());
    return activity.slice(0, limit);
  }

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

  static async getPlayers(
    search?: string,
    role?: string,
    status?: string,
    page: number = 1,
    limit: number = 20,
  ) {
    const playerRepo = AppDataSource.getRepository(Player);
    const qb = playerRepo.createQueryBuilder('player')
      .leftJoinAndSelect('player.balances', 'balances')
      .orderBy('player.created_at', 'DESC');

    if (search) {
      qb.andWhere(
        '(player.username ILIKE :search OR player.email ILIKE :search)',
        { search: `%${search}%` },
      );
    }

    if (role === 'admin') {
      qb.andWhere('player.is_admin = :isAdmin', { isAdmin: true });
    } else if (role === 'moderator') {
      qb.andWhere('player.is_moderator = :isMod', { isMod: true });
    } else if (role === 'player') {
      qb.andWhere('player.is_admin = false AND player.is_moderator = false');
    }

    if (status === 'active') {
      qb.andWhere('player.is_active = true');
    } else if (status === 'banned') {
      qb.andWhere('player.is_active = false');
    }

    const skip = (page - 1) * limit;
    qb.skip(skip).take(limit);

    const [players, total] = await qb.getManyAndCount();

    return {
      players: players.map((p) => ({
        id: p.id,
        username: p.username,
        email: p.email,
        is_active: p.is_active,
        is_admin: p.is_admin,
        is_moderator: p.is_moderator,
        language: p.language,
        created_at: p.created_at,
        last_login: p.last_login,
        balances: p.balances
          ? {
              infinite_light: p.balances.infinite_light,
              infinite_shadow: p.balances.infinite_shadow,
              dagaz: p.balances.dagaz,
              quintessence: p.balances.quintessence,
            }
          : null,
      })),
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  static async getPlayerDetail(id: string) {
    const playerRepo = AppDataSource.getRepository(Player);
    const axesRepo = AppDataSource.getRepository(PlayerAxes);
    const skillsRepo = AppDataSource.getRepository(PlayerSkills);
    const healthRepo = AppDataSource.getRepository(PlayerHealth);

    const player = await playerRepo.findOne({
      where: { id },
      relations: ['balances', 'gauges', 'health'],
    });

    if (!player) {
      return null;
    }

    const [axes, skills] = await Promise.all([
      axesRepo.find({ where: { player_id: id } }),
      skillsRepo.find({ where: { player_id: id } }),
    ]);

    return {
      id: player.id,
      username: player.username,
      email: player.email,
      oauth_provider: player.oauth_provider,
      profile_image_url: player.profile_image_url,
      language: player.language,
      newsletter_optin: player.newsletter_optin,
      is_active: player.is_active,
      is_admin: player.is_admin,
      is_moderator: player.is_moderator,
      onboarding_completed: player.onboarding_completed,
      onboarding_step: player.onboarding_step,
      country: player.country,
      city: player.city,
      criminal_tier: player.criminal_tier,
      political_tier: player.political_tier,
      legal_tier: player.legal_tier,
      ecology_tier: player.ecology_tier,
      experience: player.experience,
      created_at: player.created_at,
      updated_at: player.updated_at,
      last_login: player.last_login,
      balances: player.balances,
      gauges: player.gauges,
      health: player.health,
      axes,
      skills,
    };
  }

  static async updatePlayerRole(id: string, role: 'player' | 'moderator' | 'admin') {
    const playerRepo = AppDataSource.getRepository(Player);
    const player = await playerRepo.findOne({ where: { id } });

    if (!player) {
      throw new Error('Joueur introuvable');
    }

    player.is_admin = role === 'admin';
    player.is_moderator = role === 'moderator';

    await playerRepo.save(player);
    return { id: player.id, username: player.username, is_admin: player.is_admin, is_moderator: player.is_moderator };
  }

  static async banPlayer(id: string, reason: string, duration: number, moderatorId: string) {
    const playerRepo = AppDataSource.getRepository(Player);
    const player = await playerRepo.findOne({ where: { id } });

    if (!player) {
      throw new Error('Joueur introuvable');
    }

    player.is_active = false;
    await playerRepo.save(player);

    // Create a Sanction record with duration for audit trail
    const { Sanction } = await import('../models/Sanction');
    const sanctionRepo = AppDataSource.getRepository(Sanction);
    const expiresAt = duration > 0
      ? new Date(Date.now() + duration * 60 * 60 * 1000)
      : null; // duration=0 → permanent ban
    const sanction = sanctionRepo.create({
      player_id: id,
      imposed_by_id: moderatorId,
      type: 'ban' as any,
      reason,
      duration: `${duration}h`,
      expires_at: expiresAt,
      active: true,
    });
    await sanctionRepo.save(sanction);

    return {
      id: player.id,
      username: player.username,
      is_active: false,
      ban_reason: reason,
      ban_duration_hours: duration,
      banned_by: moderatorId,
      banned_at: new Date().toISOString(),
    };
  }

  static async unbanPlayer(id: string) {
    const playerRepo = AppDataSource.getRepository(Player);
    const player = await playerRepo.findOne({ where: { id } });

    if (!player) {
      throw new Error('Joueur introuvable');
    }

    player.is_active = true;
    await playerRepo.save(player);

    return { id: player.id, username: player.username, is_active: true };
  }

  static async adjustPlayerBalance(
    id: string,
    currency: 'infinite_light' | 'infinite_shadow' | 'dagaz' | 'quintessence',
    amount: number,
  ) {
    const balancesRepo = AppDataSource.getRepository(PlayerBalances);
    const balances = await balancesRepo.findOne({ where: { player_id: id } });

    if (!balances) {
      throw new Error('Soldes du joueur introuvables');
    }

    const currentValue = Number(balances[currency]);
    const newValue = currentValue + amount;

    if (newValue < 0) {
      throw new Error(`Solde insuffisant. Actuel: ${currentValue}, ajustement: ${amount}`);
    }

    (balances as any)[currency] = newValue;
    await balancesRepo.save(balances);

    return {
      player_id: id,
      currency,
      previous: currentValue,
      adjustment: amount,
      new_balance: newValue,
    };
  }

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

  static async getBlogArticles(search?: string, category?: string, status?: string) {
    const blogRepo = AppDataSource.getRepository(BlogPost);
    const qb = blogRepo.createQueryBuilder('blog')
      .leftJoinAndSelect('blog.author', 'author')
      .orderBy('blog.created_at', 'DESC');

    if (search) {
      qb.andWhere(
        '(blog.title ILIKE :search OR blog.content ILIKE :search)',
        { search: `%${search}%` },
      );
    }

    if (category) {
      qb.andWhere('blog.category = :category', { category });
    }

    if (status) {
      qb.andWhere('blog.status = :status', { status });
    }

    const articles = await qb.getMany();

    return articles.map((a) => ({
      id: a.id,
      title: a.title,
      slug: a.slug,
      excerpt: a.excerpt,
      category: a.category,
      status: a.status,
      cover_image_url: a.cover_image_url,
      view_count: a.view_count,
      published_at: a.published_at,
      created_at: a.created_at,
      updated_at: a.updated_at,
      author: a.author ? { id: a.author.id, username: a.author.username } : null,
    }));
  }

  static async createBlogArticle(data: {
    author_id: string;
    title: string;
    content: string;
    excerpt?: string;
    cover_image_url?: string;
    category?: string;
    status?: string;
    slug: string;
  }) {
    const blogRepo = AppDataSource.getRepository(BlogPost);

    const article = blogRepo.create({
      author_id: data.author_id,
      title: data.title,
      content: data.content,
      excerpt: data.excerpt || null,
      cover_image_url: data.cover_image_url || null,
      category: (data.category as any) || 'blog',
      status: (data.status as any) || 'draft',
      slug: data.slug,
      published_at: data.status === 'published' ? new Date() : null,
    });

    await blogRepo.save(article);
    return article;
  }

  static async updateBlogArticle(
    id: string,
    data: Partial<{
      title: string;
      content: string;
      excerpt: string;
      cover_image_url: string;
      category: string;
      status: string;
      slug: string;
    }>,
  ) {
    const blogRepo = AppDataSource.getRepository(BlogPost);
    const article = await blogRepo.findOne({ where: { id } });

    if (!article) {
      throw new Error('Article introuvable');
    }

    if (data.title !== undefined) article.title = data.title;
    if (data.content !== undefined) article.content = data.content;
    if (data.excerpt !== undefined) article.excerpt = data.excerpt;
    if (data.cover_image_url !== undefined) article.cover_image_url = data.cover_image_url;
    if (data.category !== undefined) article.category = data.category as any;
    if (data.slug !== undefined) article.slug = data.slug;

    if (data.status !== undefined) {
      article.status = data.status as any;
      if (data.status === 'published' && !article.published_at) {
        article.published_at = new Date();
      }
    }

    await blogRepo.save(article);
    return article;
  }

  static async deleteBlogArticle(id: string) {
    const blogRepo = AppDataSource.getRepository(BlogPost);
    const article = await blogRepo.findOne({ where: { id } });

    if (!article) {
      throw new Error('Article introuvable');
    }

    article.status = 'archived' as any;
    await blogRepo.save(article);
    return { id, archived: true };
  }

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

  static async getForumModerationQueue() {
    const discussionRepo = AppDataSource.getRepository(Discussion);
    const replyRepo = AppDataSource.getRepository(Reply);

    const [pendingDiscussions, pendingReplies] = await Promise.all([
      discussionRepo.find({
        where: { status: 'pending' },
        relations: ['author', 'category'],
        order: { created_at: 'ASC' },
      }),
      replyRepo.find({
        where: { status: 'pending' },
        relations: ['author', 'discussion'],
        order: { created_at: 'ASC' },
      }),
    ]);

    return {
      discussions: pendingDiscussions.map((d) => ({
        id: d.id,
        type: 'discussion' as const,
        title: d.title,
        content: d.content,
        status: d.status,
        author: d.author ? { id: d.author.id, username: d.author.username } : null,
        category: d.category ? { id: d.category.id, name: d.category.name } : null,
        created_at: d.created_at,
      })),
      replies: pendingReplies.map((r) => ({
        id: r.id,
        type: 'reply' as const,
        content: r.content,
        status: r.status,
        author: r.author ? { id: r.author.id, username: r.author.username } : null,
        discussion: r.discussion ? { id: r.discussion.id, title: r.discussion.title } : null,
        created_at: r.created_at,
      })),
    };
  }

  static async approveForumItem(id: string, type: 'discussion' | 'reply') {
    if (type === 'discussion') {
      const repo = AppDataSource.getRepository(Discussion);
      const item = await repo.findOne({ where: { id } });
      if (!item) throw new Error('Discussion introuvable');
      item.status = 'approved';
      await repo.save(item);
      return { id, type, status: 'approved' };
    } else {
      const repo = AppDataSource.getRepository(Reply);
      const item = await repo.findOne({ where: { id } });
      if (!item) throw new Error('Réponse introuvable');
      item.status = 'approved';
      await repo.save(item);
      return { id, type, status: 'approved' };
    }
  }

  static async rejectForumItem(id: string, type: 'discussion' | 'reply') {
    if (type === 'discussion') {
      const repo = AppDataSource.getRepository(Discussion);
      const item = await repo.findOne({ where: { id } });
      if (!item) throw new Error('Discussion introuvable');
      item.status = 'rejected';
      await repo.save(item);
      return { id, type, status: 'rejected' };
    } else {
      const repo = AppDataSource.getRepository(Reply);
      const item = await repo.findOne({ where: { id } });
      if (!item) throw new Error('Réponse introuvable');
      item.status = 'rejected';
      await repo.save(item);
      return { id, type, status: 'rejected' };
    }
  }

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

  static async getForumCategories() {
    const repo = AppDataSource.getRepository(ForumCategory);
    return repo.find({ order: { sort_order: 'ASC' } });
  }

  static async createForumCategory(data: {
    name: string;
    description?: string;
    icon?: string;
    sort_order?: number;
    members_only?: boolean;
  }) {
    const repo = AppDataSource.getRepository(ForumCategory);
    const category = repo.create({
      name: data.name,
      description: data.description || null,
      icon: data.icon || null,
      sort_order: data.sort_order ?? 0,
      members_only: data.members_only ?? false,
    });
    await repo.save(category);
    return category;
  }

  static async updateForumCategory(
    id: string,
    data: Partial<{
      name: string;
      description: string;
      icon: string;
      sort_order: number;
      members_only: boolean;
      is_active: boolean;
    }>,
  ) {
    const repo = AppDataSource.getRepository(ForumCategory);
    const category = await repo.findOne({ where: { id } });

    if (!category) {
      throw new Error('Catégorie introuvable');
    }

    if (data.name !== undefined) category.name = data.name;
    if (data.description !== undefined) category.description = data.description;
    if (data.icon !== undefined) category.icon = data.icon;
    if (data.sort_order !== undefined) category.sort_order = data.sort_order;
    if (data.members_only !== undefined) category.members_only = data.members_only;
    if (data.is_active !== undefined) category.is_active = data.is_active;

    await repo.save(category);
    return category;
  }

  static async deleteForumCategory(id: string) {
    const repo = AppDataSource.getRepository(ForumCategory);
    const category = await repo.findOne({ where: { id } });

    if (!category) {
      throw new Error('Catégorie introuvable');
    }

    // Soft-delete by deactivating
    category.is_active = false;
    await repo.save(category);
    return { id, deactivated: true };
  }

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

  static async getNewsletterHistory() {
    // Mock data — real implementation requires SMTP integration
    return [
      {
        id: '1',
        subject: 'Bienvenue dans Ombres & Lumières',
        sent_at: '2026-01-15T10:00:00Z',
        recipients_count: 150,
        open_rate: 0.68,
        status: 'sent',
      },
      {
        id: '2',
        subject: 'Mise à jour v0.2 — Le Marché Noir',
        sent_at: '2026-02-01T14:00:00Z',
        recipients_count: 230,
        open_rate: 0.72,
        status: 'sent',
      },
      {
        id: '3',
        subject: 'Événement spécial — La Nuit des Ombres',
        sent_at: '2026-03-01T09:00:00Z',
        recipients_count: 310,
        open_rate: 0.65,
        status: 'sent',
      },
    ];
  }

  static async getNewsletterSubscriberCount() {
    const playerRepo = AppDataSource.getRepository(Player);
    const count = await playerRepo.count({ where: { newsletter_optin: true } });
    return { count };
  }

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

  static async getReports(status?: string) {
    const reportRepo = AppDataSource.getRepository(Report);
    const qb = reportRepo.createQueryBuilder('report')
      .leftJoinAndSelect('report.reporter', 'reporter')
      .leftJoinAndSelect('report.reported_player', 'reported_player')
      .orderBy('report.created_at', 'DESC');

    if (status) {
      qb.andWhere('report.status = :status', { status });
    }

    const reports = await qb.getMany();

    return reports.map((r) => ({
      id: r.id,
      type: r.type,
      reported_content: r.reported_content,
      reason: r.reason,
      status: r.status,
      created_at: r.created_at,
      updated_at: r.updated_at,
      reporter: r.reporter ? { id: r.reporter.id, username: r.reporter.username } : null,
      reported_player: r.reported_player
        ? { id: r.reported_player.id, username: r.reported_player.username }
        : null,
    }));
  }

  static async dismissReport(reportId: string, moderatorId: string) {
    const reportRepo = AppDataSource.getRepository(Report);
    const report = await reportRepo.findOne({
      where: { id: reportId },
      relations: ['reported_player'],
    });

    if (!report) {
      throw new Error('Signalement introuvable');
    }

    report.status = 'rejete';
    await reportRepo.save(report);

    await AdminService.createModerationLog(
      moderatorId,
      report.reported_player_id,
      'Signalement rejeté',
      `Signalement #${reportId} rejeté — type: ${report.type}`,
    );

    return { id: reportId, status: 'rejete' };
  }

  static async sanctionFromReport(
    reportId: string,
    sanctionData: {
      type: 'ban' | 'suspension' | 'mute';
      reason: string;
      duration: string;
      expires_at: string | null;
    },
    moderatorId: string,
  ) {
    const reportRepo = AppDataSource.getRepository(Report);
    const sanctionRepo = AppDataSource.getRepository(Sanction);

    const report = await reportRepo.findOne({ where: { id: reportId } });

    if (!report) {
      throw new Error('Signalement introuvable');
    }

    // Create the sanction
    const sanction = sanctionRepo.create({
      player_id: report.reported_player_id,
      imposed_by_id: moderatorId,
      type: sanctionData.type,
      reason: sanctionData.reason,
      duration: sanctionData.duration,
      expires_at: sanctionData.expires_at ? new Date(sanctionData.expires_at) : null,
      active: true,
    });
    await sanctionRepo.save(sanction);

    // Mark report as treated
    report.status = 'traite';
    await reportRepo.save(report);

    // If ban, also deactivate the player account
    if (sanctionData.type === 'ban') {
      const playerRepo = AppDataSource.getRepository(Player);
      await playerRepo.update(report.reported_player_id, { is_active: false });
    }

    const actionLabel =
      sanctionData.type === 'ban'
        ? 'Ban permanent'
        : sanctionData.type === 'suspension'
          ? 'Suspension appliquée'
          : 'Mute appliqué';

    await AdminService.createModerationLog(
      moderatorId,
      report.reported_player_id,
      actionLabel,
      `${actionLabel} — durée: ${sanctionData.duration} — raison: ${sanctionData.reason}`,
    );

    return { report_id: reportId, sanction };
  }

  static async deleteReportContent(reportId: string, moderatorId: string) {
    const reportRepo = AppDataSource.getRepository(Report);
    const report = await reportRepo.findOne({ where: { id: reportId } });

    if (!report) {
      throw new Error('Signalement introuvable');
    }

    // Clear the reported content and mark report as treated
    report.reported_content = null;
    report.status = 'traite';
    await reportRepo.save(report);

    await AdminService.createModerationLog(
      moderatorId,
      report.reported_player_id,
      'Contenu supprimé',
      `Contenu du signalement #${reportId} supprimé — type: ${report.type}`,
    );

    return { id: reportId, status: 'traite', content_deleted: true };
  }

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

  static async getSanctions(active?: string) {
    const sanctionRepo = AppDataSource.getRepository(Sanction);
    const qb = sanctionRepo.createQueryBuilder('sanction')
      .leftJoinAndSelect('sanction.player', 'player')
      .leftJoinAndSelect('sanction.imposed_by', 'imposed_by')
      .orderBy('sanction.created_at', 'DESC');

    if (active === 'true') {
      qb.andWhere('sanction.active = true');
    } else if (active === 'false') {
      qb.andWhere('sanction.active = false');
    }

    const sanctions = await qb.getMany();

    return sanctions.map((s) => ({
      id: s.id,
      type: s.type,
      reason: s.reason,
      duration: s.duration,
      expires_at: s.expires_at,
      active: s.active,
      created_at: s.created_at,
      updated_at: s.updated_at,
      player: s.player ? { id: s.player.id, username: s.player.username } : null,
      imposed_by: s.imposed_by ? { id: s.imposed_by.id, username: s.imposed_by.username } : null,
    }));
  }

  static async liftSanction(sanctionId: string, moderatorId: string) {
    const sanctionRepo = AppDataSource.getRepository(Sanction);
    const sanction = await sanctionRepo.findOne({
      where: { id: sanctionId },
      relations: ['player'],
    });

    if (!sanction) {
      throw new Error('Sanction introuvable');
    }

    sanction.active = false;
    await sanctionRepo.save(sanction);

    // If it was a ban, reactivate the player account
    if (sanction.type === 'ban') {
      const playerRepo = AppDataSource.getRepository(Player);
      await playerRepo.update(sanction.player_id, { is_active: true });
    }

    await AdminService.createModerationLog(
      moderatorId,
      sanction.player_id,
      'Sanction levée',
      `Sanction #${sanctionId} (${sanction.type}) levée`,
    );

    return { id: sanctionId, active: false };
  }

  static async updateSanctionDuration(
    sanctionId: string,
    duration: string,
    expires_at: string | null,
    moderatorId: string,
  ) {
    const sanctionRepo = AppDataSource.getRepository(Sanction);
    const sanction = await sanctionRepo.findOne({ where: { id: sanctionId } });

    if (!sanction) {
      throw new Error('Sanction introuvable');
    }

    sanction.duration = duration;
    sanction.expires_at = expires_at ? new Date(expires_at) : null;
    await sanctionRepo.save(sanction);

    await AdminService.createModerationLog(
      moderatorId,
      sanction.player_id,
      'Durée de sanction modifiée',
      `Sanction #${sanctionId} (${sanction.type}) — nouvelle durée: ${duration}`,
    );

    return { id: sanctionId, duration, expires_at: sanction.expires_at };
  }

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

  static async getModerationLogs(
    moderatorUsername?: string,
    action?: string,
    dateFrom?: string,
    dateTo?: string,
  ) {
    const logRepo = AppDataSource.getRepository(ModerationLog);
    const qb = logRepo.createQueryBuilder('log')
      .leftJoinAndSelect('log.moderator', 'moderator')
      .leftJoinAndSelect('log.target_player', 'target_player')
      .orderBy('log.created_at', 'DESC');

    if (moderatorUsername) {
      qb.andWhere('moderator.username ILIKE :mod', { mod: `%${moderatorUsername}%` });
    }

    if (action) {
      qb.andWhere('log.action ILIKE :action', { action: `%${action}%` });
    }

    if (dateFrom && dateTo) {
      qb.andWhere('log.created_at BETWEEN :dateFrom AND :dateTo', {
        dateFrom: new Date(dateFrom),
        dateTo: new Date(dateTo),
      });
    } else if (dateFrom) {
      qb.andWhere('log.created_at >= :dateFrom', { dateFrom: new Date(dateFrom) });
    } else if (dateTo) {
      qb.andWhere('log.created_at <= :dateTo', { dateTo: new Date(dateTo) });
    }

    const logs = await qb.getMany();

    return logs.map((l) => ({
      id: l.id,
      action: l.action,
      details: l.details,
      created_at: l.created_at,
      moderator: l.moderator ? { id: l.moderator.id, username: l.moderator.username } : null,
      target_player: l.target_player
        ? { id: l.target_player.id, username: l.target_player.username }
        : null,
    }));
  }

  private static async createModerationLog(
    moderatorId: string,
    targetPlayerId: string,
    action: string,
    details: string,
  ) {
    const logRepo = AppDataSource.getRepository(ModerationLog);
    const log = logRepo.create({
      moderator_id: moderatorId,
      target_player_id: targetPlayerId,
      action,
      details,
    });
    await logRepo.save(log);
    return log;
  }

  // ─── Moderation — Warnings ─────────────────────────────────
  // Phase 16 (2026-04-22) — les warnings sont stockés comme ModerationLog
  // avec action='warning:<severity>'. Pas de nouvelle table (réutilise
  // moderation_logs). Déclenche une Notification au joueur ciblé.

  static async listWarnings(limit = 50) {
    const logRepo = AppDataSource.getRepository(ModerationLog);
    const rows = await logRepo.createQueryBuilder('log')
      .leftJoinAndSelect('log.moderator', 'moderator')
      .leftJoinAndSelect('log.target_player', 'target_player')
      .where('log.action LIKE :prefix', { prefix: 'warning:%' })
      .orderBy('log.created_at', 'DESC')
      .take(limit)
      .getMany();

    return rows.map((l) => ({
      id: l.id,
      severity: (l.action.split(':')[1] || 'medium') as 'low' | 'medium' | 'high',
      reason: l.details ?? '',
      created_at: l.created_at,
      moderator: l.moderator
        ? { id: l.moderator.id, username: l.moderator.username }
        : null,
      target_player: l.target_player
        ? { id: l.target_player.id, username: l.target_player.username }
        : null,
    }));
  }

  static async createWarning(
    moderatorId: string,
    targetPlayerUsername: string,
    severity: 'low' | 'medium' | 'high',
    reason: string,
  ) {
    if (!reason || !reason.trim()) throw new Error('Raison requise');
    if (!['low', 'medium', 'high'].includes(severity)) {
      throw new Error('Sévérité invalide (low/medium/high)');
    }
    const playerRepo = AppDataSource.getRepository(Player);
    const target = await playerRepo
      .createQueryBuilder('p')
      .where('LOWER(p.username) = LOWER(:u)', { u: targetPlayerUsername })
      .getOne();
    if (!target) throw new Error('Joueur introuvable');

    const log = await AdminService.createModerationLog(
      moderatorId,
      target.id,
      `warning:${severity}`,
      reason,
    );

    try {
      const { NotificationService } = await import('./notification.service');
      await NotificationService.create({
        player_id: target.id,
        type: 'moderation',
        title: `Avertissement ${severity === 'high' ? '(élevé)' : severity === 'medium' ? '(moyen)' : '(faible)'}`,
        message: reason.slice(0, 250),
        link: `moderation:warning:${log.id}`,
      });
    } catch {
      /* silencieux : l'avertissement est posé même si la notif échoue */
    }

    return {
      id: log.id,
      severity,
      reason,
      created_at: log.created_at,
      target_player: { id: target.id, username: target.username },
    };
  }

  // ─── World Stock View (Admin) ──────────────────────────────

  /** Global view of all items in circulation, grouped by type/subtype */
  static async getWorldStock() {
    const invRepo = AppDataSource.getRepository(PlayerInventory);
    const batchRepo = AppDataSource.getRepository(ProductionBatch);
    const bizRepo = AppDataSource.getRepository(Business);

    // Aggregate all inventory items across all players
    const inventoryStock = await invRepo
      .createQueryBuilder('i')
      .select('i.item_type', 'item_type')
      .addSelect('i.item_subtype', 'item_subtype')
      .addSelect('i.storage_condition', 'storage_condition')
      .addSelect('SUM(i.quantity)', 'total_quantity')
      .addSelect('SUM(i.weight_grams)', 'total_weight_grams')
      .addSelect('COUNT(DISTINCT i.player_id)', 'holder_count')
      .groupBy('i.item_type')
      .addGroupBy('i.item_subtype')
      .addGroupBy('i.storage_condition')
      .orderBy('i.item_type', 'ASC')
      .addOrderBy('"total_quantity"', 'DESC')
      .getRawMany();

    // Active production batches
    const activeBatches = await batchRepo
      .createQueryBuilder('b')
      .select('b.chain_type', 'chain_type')
      .addSelect('b.product_name', 'product_name')
      .addSelect('b.stage', 'stage')
      .addSelect('SUM(b.quantity_kg)', 'total_kg')
      .addSelect('COUNT(*)', 'batch_count')
      .where('b.stage != :done', { done: 'delivered' })
      .groupBy('b.chain_type')
      .addGroupBy('b.product_name')
      .addGroupBy('b.stage')
      .getRawMany();

    // Business stock levels
    const businessStock = await bizRepo
      .createQueryBuilder('biz')
      .select('biz.type', 'business_type')
      .addSelect('SUM(biz.current_stock_kg)', 'total_stock_kg')
      .addSelect('SUM(biz.storage_capacity_kg)', 'total_capacity_kg')
      .addSelect('COUNT(*)', 'business_count')
      .groupBy('biz.type')
      .orderBy('"total_stock_kg"', 'DESC')
      .getRawMany();

    // Global currency totals
    const currencyTotals = await AppDataSource.getRepository(PlayerBalances)
      .createQueryBuilder('b')
      .select('SUM(b.infinite_light)', 'total_light')
      .addSelect('SUM(b.infinite_shadow)', 'total_shadow')
      .addSelect('SUM(b.dagaz)', 'total_dagaz')
      .addSelect('COUNT(*)', 'player_count')
      .getRawOne();

    return {
      inventory_stock: inventoryStock,
      active_production: activeBatches,
      business_stock: businessStock,
      currency_totals: currencyTotals,
      generated_at: new Date().toISOString(),
    };
  }
}
