import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn, Unique } from 'typeorm';
import { License } from './license.entity';
import { AgentHost } from './agent-host.entity';

/**
 * One game server process / orchestrated unit (a Rust server, a Conan world,
 * a Dune battlegroup). The billing unit — plans count instances.
 * `agent_instance_id` is the agent's slug and the NATS subject segment.
 */
@Entity('game_instances')
@Unique(['license_id', 'agent_instance_id'])
export class GameInstance {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'uuid' })
  license_id: string;

  @Column({ type: 'uuid', nullable: true })
  host_id: string | null;

  @Column({ type: 'uuid', nullable: true })
  cluster_id: string | null;

  @Column({ type: 'varchar', length: 64 })
  agent_instance_id: string;

  @Column({ type: 'varchar', length: 32 })
  game: string;

  @Column({ type: 'varchar', length: 255, nullable: true })
  label: string | null;

  @Column({ type: 'varchar', length: 32, default: 'unknown' })
  state: string;

  @Column({ type: 'text', nullable: true })
  root_path: string | null;

  @Column({ type: 'bigint', default: 0 })
  uptime_seconds: number;

  @Column({ type: 'timestamptz', nullable: true })
  last_seen_at: Date | null;

  @Column({ type: 'timestamptz', default: () => 'NOW()' })
  created_at: Date;

  @Column({ type: 'timestamptz', default: () => 'NOW()' })
  updated_at: Date;

  @ManyToOne(() => License, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'license_id' })
  license: License;

  @ManyToOne(() => AgentHost, { onDelete: 'SET NULL', nullable: true })
  @JoinColumn({ name: 'host_id' })
  host: AgentHost | null;
}
