import { AppDataSource } from '../config/database';
import { ChatMessage } from '../models/ChatMessage';
import { Player } from '../models/Player';
import { GangMember } from '../models/GangMember';

const chatRepo = () => AppDataSource.getRepository(ChatMessage);
const playerRepo = () => AppDataSource.getRepository(Player);
const gangMemberRepo = () => AppDataSource.getRepository(GangMember);

export type ChatChannel = 'general' | 'gang' | 'proximity';

/**
 * Phase 16 (2026-04-22) — unification U12 : extraction de chat.routes
 * logique métier vers ChatService. La route devient un 2-liner qui
 * appelle le service + res.json.
 */
export class ChatService {
  static readonly MAX_CONTENT_LENGTH = 500;
  static readonly DEFAULT_LIMIT = 50;
  static readonly MAX_LIMIT = 100;

  /** Liste les N derniers messages d'un canal pour un joueur donné (filtres geo/gang). */
  static async listMessages(
    playerId: string,
    channelInput: string = 'general',
    limit: number = ChatService.DEFAULT_LIMIT,
  ): Promise<ChatMessage[]> {
    const channel: ChatChannel = ['general', 'gang', 'proximity'].includes(channelInput)
      ? channelInput as ChatChannel
      : 'general';
    const safeLimit = Math.min(Math.max(1, limit), ChatService.MAX_LIMIT);
    const player = await playerRepo().findOneBy({ id: playerId });
    if (!player) throw new Error('Joueur introuvable');

    let gangId: string | null = null;
    if (channel === 'gang') {
      const membership = await gangMemberRepo().findOne({ where: { player_id: playerId } });
      gangId = membership?.gang_id ?? null;
      if (!gangId) return [];
    }

    const qb = chatRepo().createQueryBuilder('msg')
      .leftJoinAndSelect('msg.sender', 'sender')
      .where('msg.channel = :channel', { channel })
      .orderBy('msg.created_at', 'DESC')
      .take(safeLimit);

    if (channel === 'proximity' && player.city) {
      qb.andWhere('msg.city = :city', { city: player.city });
    }
    if (channel === 'gang') {
      qb.andWhere('msg.gang_id = :gangId', { gangId });
    }

    const messages = await qb.getMany();
    return messages.reverse();
  }

  /** Poste un message sur un canal. Valide longueur + droits d'accès gang. */
  static async postMessage(
    playerId: string,
    channelInput: string,
    content: string,
  ): Promise<ChatMessage> {
    if (!channelInput) throw new Error('channel requis');
    if (!['general', 'gang', 'proximity'].includes(channelInput)) {
      throw new Error('channel invalide');
    }
    const channel = channelInput as ChatChannel;
    if (!content || !content.trim()) throw new Error('content requis');
    if (content.length > ChatService.MAX_CONTENT_LENGTH) {
      throw new Error(`Message trop long (max ${ChatService.MAX_CONTENT_LENGTH} caractères)`);
    }

    const player = await playerRepo().findOneBy({ id: playerId });
    if (!player) throw new Error('Joueur introuvable');

    let gangId: string | null = null;
    if (channel === 'gang') {
      const membership = await gangMemberRepo().findOne({ where: { player_id: playerId } });
      gangId = membership?.gang_id ?? null;
      if (!gangId) throw new Error('Accès gang interdit');
    }

    const message = chatRepo().create({
      sender_id: playerId,
      sender_username: player.username,
      channel,
      content: content.trim(),
      gang_id: channel === 'gang' ? gangId : null,
      country: player.country || null,
      country_code: player.country_code || null,
      region: player.region || null,
      department: player.department || null,
      city: player.city || null,
      sender_lat: player.current_lat ?? null,
      sender_lon: player.current_lon ?? null,
    });
    return chatRepo().save(message);
  }
}
