import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { TeamRolesEnum } from 'src/team-roles/team-roles.enum';
import { Team } from 'src/teams/entities/team.entity';
import { TeamAccessService } from 'src/teams/team-access.service';
import { Repository } from 'typeorm';
import { buildCsv, buildPdf, buildRows } from './cashbox-export.utils';

@Injectable()
export class CashboxExportService {
  constructor(
    @InjectRepository(Team)
    private readonly teamRepository: Repository<Team>,
    private readonly access: TeamAccessService,
  ) {}

  async exportForUser(
    teamId: number,
    userId: number,
    from: string,
    to: string,
    format: 'csv' | 'pdf',
  ): Promise<{ buffer: Buffer; contentType: string; filename: string }> {
    await this.access.assertAtLeast(
      userId,
      teamId,
      'transaction_create_min_role',
      TeamRolesEnum.scnd_treasurer,
    );
    const team = await this.teamRepository.findOne({
      where: { id: teamId },
      relations: ['players', 'players.transactions', 'transactions'],
    });
    if (!team) throw new NotFoundException('Team nicht gefunden.');

    const rows = buildRows(team, from, to);

    if (format === 'csv') {
      return {
        buffer: Buffer.from(buildCsv(rows), 'utf-8'),
        contentType: 'text/csv; charset=utf-8',
        filename: `kassenbuch_${team.alias}_${from}_${to}.csv`,
      };
    }
    return {
      buffer: await buildPdf(team, rows, from, to),
      contentType: 'application/pdf',
      filename: `kassenbuch_${team.alias}_${from}_${to}.pdf`,
    };
  }
}
