import {
  IsEnum,
  IsInt,
  IsNotEmpty,
  IsOptional,
  IsPositive,
  IsString
} from "class-validator";
import { BeforeInsert, BeforeUpdate, Column, Entity, ManyToOne, PrimaryGeneratedColumn } from "typeorm";
import { PermissionAction } from '../enums/PermissionAction';
import type { User } from './User';

/**
 * Defines the UserAction entity.
 * Will later be used to document a user's actions.
*/
@Entity()
export class UserAction {
  /**
   * Autogenerated unique id (primary key).
   */
  @PrimaryGeneratedColumn()
  @IsInt()
  id: number;

  /**
   * The user that performed the action.
   */
  @ManyToOne(() => require("./User").User, (user: User) => user.actions)
  user!: User

  /**
   * The actions's target (e.g. Track#2)
   */
  @Column()
  @IsNotEmpty()
  @IsString()
  target: string;

  /**
   * The actions's action (e.g. UPDATE).
   * Directly pulled from the PermissionAction Enum.
   */
  @Column({ type: 'varchar' })
  @IsEnum(PermissionAction)
  action: PermissionAction;

  /**
   * The description of the change (before-> after; e.g. distance:15->17).
   * Will later be defined in more detail.
   */
  @Column({ nullable: true })
  @IsOptional()
  @IsString()
  changed: string;

  @Column({ type: 'bigint', nullable: true, readonly: true })
  @IsInt()
  @IsPositive()
  created_at: number;

  @Column({ type: 'bigint', nullable: true })
  @IsInt()
  @IsPositive()
  updated_at: number;

  @BeforeInsert()
  public setCreatedAt() {
    this.created_at = Math.floor(Date.now() / 1000);
    this.updated_at = Math.floor(Date.now() / 1000);
  }

  @BeforeUpdate()
  public setUpdatedAt() {
    this.updated_at = Math.floor(Date.now() / 1000);
  }

  /**
   * Turns this entity into it's response class.
   */
  public toResponse() {
    return new Error("NotImplemented");
  }
}