import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  Index,
} from 'typeorm';

/**
 * SecurityIpLog - Raw IP storage for law enforcement requests
 *
 * Legal Basis:
 * - GDPR Article 6(1)(c): Legal obligation for law enforcement cooperation
 * - GDPR Article 6(1)(f): Legitimate interest for fraud prevention
 *
 * IMPORTANT: This data is SEPARATE from consent-free analytics.
 * Analytics session IDs are ephemeral/anonymous; this table correlates
 * session activity with raw IPs for security and legal purposes only.
 *
 * Access Restrictions:
 * - Admin-only endpoints with mandatory audit logging
 * - 90-day retention with automatic purge
 * - Every query is logged to safety_audit_log
 */
@Entity('security_ip_log')
export class SecurityIpLog {
  @PrimaryGeneratedColumn('uuid')
  id!: string;

  /**
   * Raw IP address (NOT hashed) for law enforcement requests.
   * PostgreSQL inet type for efficient IP range queries.
   */
  @Column({ type: 'inet', name: 'ip_address' })
  @Index('idx_security_ip_log_ip')
  ipAddress!: string;

  /**
   * Analytics session ID for correlation.
   * Links to consent-free ephemeral sessions.
   */
  @Column({ type: 'varchar', length: 64, name: 'session_id' })
  @Index('idx_security_ip_log_session')
  sessionId!: string;

  /**
   * Authenticated user ID if available.
   * NULL for anonymous/unauthenticated requests.
   */
  @Column({ type: 'varchar', length: 255, name: 'user_id', nullable: true })
  @Index('idx_security_ip_log_user')
  userId!: string | null;

  /**
   * Request path for activity correlation.
   */
  @Column({ type: 'varchar', length: 500, name: 'request_path' })
  requestPath!: string;

  /**
   * HTTP method (GET, POST, etc.)
   */
  @Column({ type: 'varchar', length: 10, name: 'request_method' })
  requestMethod!: string;

  /**
   * User agent string for device identification.
   */
  @Column({ type: 'varchar', length: 500, name: 'user_agent', nullable: true })
  userAgent!: string | null;

  /**
   * Request timestamp for time-based queries.
   */
  @Column({ type: 'timestamptz' })
  @Index('idx_security_ip_log_timestamp')
  timestamp!: Date;

  @CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
  createdAt!: Date;
}
