import { Injectable } from '@nestjs/common';

import { assignJoinAddress, formatJoinAddress, getPlayDomain } from '@hexahost/dns';
import type { GameServer, ServerDnsRecord } from '@hexahost/database';

import { PrismaService } from '../prisma/prisma.service';

@Injectable()
export class JoinService {
  constructor(private readonly prisma: PrismaService) {}

  getPlayDomain(): string {
    return getPlayDomain();
  }

  formatJoinHostname(server: Pick<GameServer, 'joinSlug' | 'edition'>): string | null {
    return formatJoinAddress(server.joinSlug, server.edition);
  }

  async ensureJoinAddress(serverId: string): Promise<string | null> {
    const result = await assignJoinAddress(serverId);
    return result?.joinHostname ?? null;
  }

  async getDnsRecords(serverId: string): Promise<ServerDnsRecord[]> {
    return this.prisma.serverDnsRecord.findMany({
      where: { serverId },
      orderBy: { recordType: 'asc' },
    });
  }
}
