import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, JoinColumn, Index } from 'typeorm';
import { License } from './license.entity';

@Entity('api_keys')
@Index(['key_hash'])
@Index(['license_id'])
export class ApiKey {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Column({ type: 'varchar', length: 100 })
  name: string;

  /** First 8 chars of the random token — shown in UI so users can identify keys. */
  @Column({ type: 'varchar', length: 16 })
  key_prefix: string;

  /** SHA-256 hex digest of the full plaintext key. Never returned to clients. */
  @Column({ type: 'varchar', length: 128 })
  key_hash: string;

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

  @Column({ type: 'boolean', default: true })
  is_active: boolean;

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

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