import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Record } from './record.entity';
import { Repository } from 'typeorm';
import { RecordGateway } from './record.gateway';

@Injectable()
export class RecordService {
    constructor(
        @InjectRepository(Record)
        private readonly recordRepository: Repository<Record>,
        private readonly gateway: RecordGateway
    ) { }

    async createRecord(agency: string, name: string): Promise<Record> {
        const record = this.recordRepository.create({ agency, name });
        const saved = await this.recordRepository.save(record);
        const count = await this.recordRepository.count();
        this.gateway.sendCount(count);
        return saved;
    }

    async countRecords(): Promise<number> {
        return await this.recordRepository.count();
    }

    async createAllToMax(): Promise<number> {
        const total = await this.recordRepository.count();
        const configMax = parseInt(process.env.MAXUSER ?? "0", 10);
        if (!configMax) {
            throw new Error("MAXUSER not configured");
        }
        const missing = configMax - total;
        if (missing > 0) {
            const bulk: Record[] = [];
            for (let i = 0; i < missing; i++) {
                bulk.push({ agency: "auto" } as Record);
            }
            await this.recordRepository.save(bulk);
        }
        const newCount = await this.recordRepository.count();
        this.gateway.sendCount(newCount);
        return newCount;
    }
} 
