import { AppDataSource } from '../config/database';
import { PlayerTransaction, TransactionCategory, TransactionType } from '../models/PlayerTransaction';

type LogInput = {
  player_id: string;
  category: TransactionCategory;
  type: TransactionType;
  amount: number;
  currency: string;
  description?: string | null;
};

export class TransactionService {
  static async log(input: LogInput): Promise<void> {
    const amount = Math.abs(Math.trunc(Number(input.amount) || 0));
    if (!input.player_id || amount === 0) return;

    const repo = AppDataSource.getRepository(PlayerTransaction);
    await repo.save(repo.create({
      player_id: input.player_id,
      category: input.category,
      type: input.type,
      amount,
      currency: input.currency || 'infinite_light',
      description: input.description ?? null,
    }));
  }

  static async getByCategory(playerId: string, category?: TransactionCategory, from?: Date, to?: Date) {
    const repo = AppDataSource.getRepository(PlayerTransaction);
    const qb = repo.createQueryBuilder('tx')
      .where('tx.player_id = :playerId', { playerId })
      .orderBy('tx.created_at', 'DESC');

    if (category) qb.andWhere('tx.category = :category', { category });
    if (from) qb.andWhere('tx.created_at >= :from', { from });
    if (to) qb.andWhere('tx.created_at <= :to', { to });

    return qb.take(500).getMany();
  }

  static async getSummary(playerId: string, from?: Date, to?: Date) {
    const repo = AppDataSource.getRepository(PlayerTransaction);
    const qb = repo.createQueryBuilder('tx')
      .select('tx.category', 'category')
      .addSelect('tx.type', 'type')
      .addSelect('tx.currency', 'currency')
      .addSelect('SUM(tx.amount)', 'total')
      .where('tx.player_id = :playerId', { playerId })
      .groupBy('tx.category')
      .addGroupBy('tx.type')
      .addGroupBy('tx.currency');

    if (from) qb.andWhere('tx.created_at >= :from', { from });
    if (to) qb.andWhere('tx.created_at <= :to', { to });

    return qb.getRawMany();
  }
}

