import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { EarlyAccessSignup } from '../../entities/early-access-signup.entity';
import { CreateEarlyAccessDto } from './dto/create-early-access.dto';

@Injectable()
export class EarlyAccessService {
  private readonly logger = new Logger(EarlyAccessService.name);

  constructor(
    @InjectRepository(EarlyAccessSignup)
    private readonly repo: Repository<EarlyAccessSignup>,
  ) {}

  async register(dto: CreateEarlyAccessDto): Promise<{ success: true; alreadyRegistered: boolean }> {
    const existing = await this.repo.findOne({ where: { email: dto.email } });
    if (existing) {
      // Duplicate email — return friendly success rather than a 409 that would break the UX
      return { success: true, alreadyRegistered: true };
    }

    const signup = this.repo.create({
      email: dto.email,
      server_count: dto.server_count ?? 'not specified',
    });

    try {
      await this.repo.save(signup);
    } catch (err: unknown) {
      // Guard against a race-condition duplicate (unique constraint violation)
      const pg = err as { code?: string };
      if (pg.code === '23505') {
        return { success: true, alreadyRegistered: true };
      }
      this.logger.error('Failed to save early-access signup', err);
      throw err;
    }

    return { success: true, alreadyRegistered: false };
  }
}
