import {
  Column,
  Entity,
  Index,
  JoinColumn,
  ManyToOne,
  PrimaryGeneratedColumn,
} from 'typeorm';
import { UsersEntity } from './Users.entity';
import { DevicesEntity } from './Devices.entity';
import { SCHEMA_NAME } from 'src/constants/auth';

@Index('fk_assignment_device', ['device_id'], {})
@Index('fk_assignment_employee', ['employee_id'], {})
@Index('fk_assignment_assigned_by', ['assigned_by'], {})
@Entity('device_assignments', { schema: SCHEMA_NAME })
export class DeviceAssignmentsEntity {
  @PrimaryGeneratedColumn({ type: 'int', name: 'id' })
  id: number;

  @Column('int', { name: 'device_id' })
  device_id: number;

  @Column('int', { name: 'employee_id' })
  employee_id: number;

  @Column('date', { name: 'assigned_date' })
  assigned_date: string;

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

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

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

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

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

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

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

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

  @ManyToOne(() => DevicesEntity, (devices) => devices.deviceAssignments, {
    onDelete: 'CASCADE',
    onUpdate: 'RESTRICT',
  })
  @JoinColumn([{ name: 'device_id', referencedColumnName: 'id' }])
  device: DevicesEntity;

  @ManyToOne(() => UsersEntity, (users) => users.deviceAssignments2, {
    onDelete: 'CASCADE',
    onUpdate: 'RESTRICT',
  })
  @JoinColumn([{ name: 'employee_id', referencedColumnName: 'id' }])
  employee: UsersEntity;
}
