import { AppDataSource } from '../config/database';
import { Notification, NotificationType } from '../models/Notification';
import { GangMember } from '../models/GangMember';
import { CartelMember } from '../models/CartelMember';
import { Gang } from '../models/Gang';

const notifRepo = () => AppDataSource.getRepository(Notification);
const gangMemberRepo = () => AppDataSource.getRepository(GangMember);
const cartelMemberRepo = () => AppDataSource.getRepository(CartelMember);
const gangRepo = () => AppDataSource.getRepository(Gang);

/**
 * NotificationService — Phase 16 (2026-04-22), unification U10.
 *
 * SEUL point d'écriture canonique dans `notifications` table.
 *
 * Pattern : toute notif gameplay passe par `create()` (single) ou par les
 * helpers `notifyGang*`, `notifyCartel*` (bulk). Les services qui écrivaient
 * direct via `notificationRepo().save(...)` doivent migrer progressivement.
 *
 * Le but est d'uniformiser le trail (type/title/message/link), permettre
 * les hooks (mute, preferences, priorité) et pouvoir auditer facilement
 * qui notifie qui.
 */
export class NotificationService {
  /** Crée une notification pour un joueur. Silencieux si le joueur est absent. */
  static async create(params: {
    player_id: string;
    type: NotificationType;
    title: string;
    message: string;
    link?: string | null;
  }): Promise<Notification | null> {
    try {
      const n = notifRepo().create({
        player_id: params.player_id,
        type: params.type,
        title: params.title,
        message: params.message,
        link: params.link ?? null,
        is_read: false,
      });
      return await notifRepo().save(n);
    } catch (err) {
      console.warn('[NotificationService] create failed', err);
      return null;
    }
  }

  /** Notifie tous les membres d'un gang (hors joueur exclu optionnel). */
  static async notifyGangMembers(
    gangId: string,
    payload: Omit<Parameters<typeof NotificationService.create>[0], 'player_id'>,
    excludePlayerId?: string,
  ): Promise<number> {
    const members = await gangMemberRepo().find({ where: { gang_id: gangId } });
    let sent = 0;
    for (const m of members) {
      if (excludePlayerId && m.player_id === excludePlayerId) continue;
      const result = await NotificationService.create({ ...payload, player_id: m.player_id });
      if (result) sent++;
    }
    return sent;
  }

  /**
   * Notifie le(s) administrateur(s) d'un cartel.
   *
   * Résolution du joueur destinataire dans l'ordre :
   *   1. `CartelMember.primary_player_id`
   *   2. fallback : `Gang.leader_player_id` pour chaque gang membre
   */
  static async notifyCartelAdmins(
    cartelId: string,
    payload: Omit<Parameters<typeof NotificationService.create>[0], 'player_id'>,
    excludePlayerId?: string,
  ): Promise<number> {
    const members = await cartelMemberRepo().find({
      where: { cartel_id: cartelId, status: 'active' as any },
    });
    let sent = 0;
    for (const m of members) {
      let playerId: string | null | undefined = (m as any).primary_player_id ?? null;
      if (!playerId) {
        const gang = await gangRepo().findOneBy({ id: m.gang_id });
        playerId = (gang as any)?.leader_id ?? null;
      }
      if (!playerId) continue;
      if (excludePlayerId && playerId === excludePlayerId) continue;
      if (!m.is_admin) continue;
      const result = await NotificationService.create({ ...payload, player_id: playerId });
      if (result) sent++;
    }
    return sent;
  }
}
