import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { User } from './user.entity.js';
import { Tenant } from './tenant.entity.js';

/**
 * Logical session status derived from DDL fields (revoked_at, expires_at).
 * DDL does not have a 'status' column -- this enum is used at the application
 * layer by token.service.ts for convenience.  It is NOT persisted directly.
 */
export enum SessionStatus {
  ACTIVE = 'active',
  REVOKED = 'revoked',
  EXPIRED = 'expired',
}

@Entity({ schema: 'auth', name: 'sessions' })
@Index('idx_sessions_user', ['userId'])
@Index('idx_sessions_tenant', ['tenantId'])
@Index('idx_sessions_jti', ['jti'])
@Index('idx_sessions_expires', ['expiresAt'])
@Index('idx_sessions_active', ['userId', 'revokedAt'])
export class Session {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'uuid', nullable: false, name: 'user_id' })
  userId: string;

  @Column({ type: 'uuid', nullable: false, name: 'tenant_id' })
  tenantId: string;

  // Token info
  @Column({
    type: 'varchar',
    length: 255,
    nullable: false,
    name: 'refresh_token_hash',
  })
  refreshTokenHash: string;

  @Column({
    type: 'varchar',
    length: 255,
    unique: true,
    nullable: false,
  })
  jti: string;

  // Device info
  @Column({ type: 'jsonb', default: '{}', name: 'device_info' })
  deviceInfo: Record<string, any>;

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

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

  @Column({ type: 'inet', nullable: true, name: 'ip_address' })
  ipAddress: string | null;

  // Geo info
  @Column({ type: 'varchar', length: 2, nullable: true, name: 'country_code' })
  countryCode: string | null;

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

  // Timestamps
  @Column({
    type: 'timestamptz',
    nullable: true,
    name: 'last_activity_at',
    default: () => 'CURRENT_TIMESTAMP',
  })
  lastActivityAt: Date | null;

  @Column({ type: 'timestamptz', nullable: false, name: 'expires_at' })
  expiresAt: Date;

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

  @Column({
    type: 'varchar',
    length: 100,
    nullable: true,
    name: 'revoked_reason',
  })
  revokedReason: string | null;

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

  // Relations
  @ManyToOne(() => User, (user) => user.sessions, {
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'user_id' })
  user: User;

  @ManyToOne(() => Tenant, {
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'tenant_id' })
  tenant: Tenant;
}
