import { Entity, Column, ManyToOne, JoinColumn, Index } from 'typeorm';
import { BaseEntity } from '../database/base.entity';
import { RoleEntity } from './role.entity';

/**
 * User entity — tenant-scoped.
 *
 * Per scope doc (User Management):
 * - Fields: Name, Email, Phone, Role, Status, Last Login
 * - Password stored as bcrypt hash
 * - Single role per user (ManyToOne)
 * - Email unique PER TENANT (not globally) — multi-tenant SaaS requirement
 */
@Entity('users')
@Index(['tenant_id', 'email'], { unique: true, where: '"is_deleted" = false' })
export class UserEntity extends BaseEntity {
  @Column({ type: 'varchar', length: 255 })
  name: string;

  @Column({ type: 'varchar', length: 255 })
  email: string;

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

  @Column({ type: 'varchar', length: 255 })
  password_hash: string;

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

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

  @ManyToOne(() => RoleEntity, { eager: false })
  @JoinColumn({ name: 'role_id' })
  role: RoleEntity;

  @Column({ type: 'uuid', nullable: true })
  role_id: string;

  /** Optional manager — user this person reports to (same tenant). */
  @ManyToOne(() => UserEntity, { eager: false, nullable: true })
  @JoinColumn({ name: 'parent_user_id' })
  parent_user: UserEntity | null;

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

  // --- Workspace preference ---
  // Default destination shown by the top-bar picker and pre-selected
  // as the initial filter on list pages. NOT an access gate — every
  // user can still see/query every destination via per-page filters
  // or explicit URLs. Null means "All destinations" (shows everything).
  @Column({ type: 'uuid', nullable: true })
  active_destination_id: string | null;
}
