import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  ManyToOne,
  JoinColumn,
  CreateDateColumn,
  UpdateDateColumn,
  DeleteDateColumn,
  AfterLoad,
} from "typeorm"
import { IncidentReporting } from "./incident-reporting.entity"
import { isEmpty } from "class-validator"

@Entity("incident_images")
export class IncidentImage {
  @PrimaryGeneratedColumn()
  id: number

  @Column({ type: "int" })
  incident_id: number

  @Column({ type: "varchar", nullable: false })
  image_url: string

  @CreateDateColumn({ type: "timestamp", default: () => "NOW()" })
  created_at: Date

  @UpdateDateColumn({ type: "timestamp", default: () => "NOW()" })
  updated_at: Date

  @DeleteDateColumn()
  deleted_at: Date

  @ManyToOne(() => IncidentReporting, (incident) => incident.images, {
    onDelete: "CASCADE",
  })
  @JoinColumn({ name: "incident_id" })
  incident: IncidentReporting

  @AfterLoad()
  async profilePict() {
    if (isEmpty(this.image_url)) {
      this.image_url = `${process.env.BACK_URL}/static-images/png/img-plceholder@2x.png`
    } else {
      this.image_url =
        process.env.FILE_UPLOAD === "Local"
          ? `${process.env.BACK_URL}/` + this.image_url
          : `${process.env.CLOUDFLARE_R2_PUBLIC_URL}/${this.image_url}`
    }
  }
}
