import {
  Column,
  Entity,
  Index,
  JoinColumn,
  ManyToOne,
  OneToMany,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { DeviceAssignmentsEntity } from './DeviceAssignments.entity';
import { SCHEMA_NAME } from 'src/constants/auth';

@Index('employee_code', ['employee_code'], { unique: true })
@Index('email', ['email'], { unique: true })
@Index('fk_manager', ['manager_id'], {})
@Entity('users', { schema: SCHEMA_NAME })
export class UsersEntity {
  @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
  id: number;

  @Column('varchar', { name: 'employee_code', unique: true, length: 50 })
  employee_code: string;

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

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

  @Column('varchar', { name: 'email', unique: true, length: 150 })
  email: string;

  @Column('varchar', { name: 'personal_email', unique: true, length: 150 })
  personal_email: string;

  @Column('varchar', { name: 'phone', length: 15 })
  phone: string;

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

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

  @Column('enum', {
    name: 'status',
    enum: ['active', 'inactive'],
    default: () => "'active'",
  })
  status: 'active' | 'inactive';

  @Column('date', { name: 'join_date', nullable: true })
  join_date: string | null;

  @Column('date', { name: 'exit_date', nullable: true })
  exit_date: string | null;

  @Column('int', { name: 'manager_id', nullable: true })
  manager_id: number | null;

  @Column('timestamp', {
    name: 'created_at',
    default: () => 'CURRENT_TIMESTAMP',
  })
  created_at: Date;

  @Column('timestamp', {
    name: 'updated_at',
    default: () => 'CURRENT_TIMESTAMP',
  })
  updated_at: Date;

  @OneToMany(
    () => DeviceAssignmentsEntity,
    (deviceAssignments) => deviceAssignments.assignedBy2,
  )
  deviceAssignments: DeviceAssignmentsEntity[];

  @OneToMany(
    () => DeviceAssignmentsEntity,
    (deviceAssignments) => deviceAssignments.employee,
  )
  deviceAssignments2: DeviceAssignmentsEntity[];

  @ManyToOne(() => UsersEntity, (users) => users.users, {
    onDelete: 'SET NULL',
    onUpdate: 'RESTRICT',
  })
  @JoinColumn([{ name: 'manager_id', referencedColumnName: 'id' }])
  manager: UsersEntity;

  @OneToMany(() => UsersEntity, (users) => users.manager)
  users: UsersEntity[];
}
