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

import {
  generateSecureToken,
  hashToken,
  UserRole,
} from '@hexahost/auth';

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

export interface CreateNodeInput {
  name: string;
  hostname: string;
  maxServers?: number;
}

export interface CreateNodeResponse {
  node: {
    id: string;
    name: string;
    hostname: string;
    status: string;
    maxServers: number;
    createdAt: string;
  };
  enrollmentToken: string;
}

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

  assertSuperAdmin(roles: string[]): void {
    if (!roles.includes(UserRole.SUPER_ADMIN)) {
      throw new ForbiddenException('Super administrator access required');
    }
  }

  async createNode(input: CreateNodeInput): Promise<CreateNodeResponse> {
    const enrollmentToken = generateSecureToken();

    const node = await this.prisma.gameNode.create({
      data: {
        name: input.name,
        hostname: input.hostname,
        maxServers: input.maxServers ?? 10,
        enrollmentTokenHash: hashToken(enrollmentToken),
      },
    });

    return {
      node: {
        id: node.id,
        name: node.name,
        hostname: node.hostname,
        status: node.status,
        maxServers: node.maxServers,
        createdAt: node.createdAt.toISOString(),
      },
      enrollmentToken,
    };
  }
}
