import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  ManyToOne,
  JoinColumn,
  BeforeInsert,
  BeforeUpdate,
} from "typeorm"
import { BaseEntity } from "../../common/entities/base.entity"
import { Company } from "./company.entity"

export enum DurationType {
  MONTHS = "Months",
  YEARS = "Years",
  DAYS = "Days",
}

export enum SubscriptionStatus {
  ACTIVE = "active",
  EXPIRED = "expired",
  UPCOMING = "upcoming",
}

@Entity("company_subscriptions")
export class CompanySubscription extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number

  @Column({ type: "int", nullable: false })
  company_id: number

  @Column({ type: "date", nullable: false })
  subscription_start_date: Date

  @Column({ type: "date", nullable: true })
  subscription_end_date: Date

  @Column({ type: "int", nullable: false })
  duration: number

  @Column({
    type: "enum",
    enum: DurationType,
    default: DurationType.MONTHS,
  })
  duration_type: DurationType

  @Column({ type: "decimal", precision: 10, scale: 2, nullable: false })
  subscription_amount: number

  @Column({
    type: "enum",
    enum: SubscriptionStatus,
    default: SubscriptionStatus.ACTIVE,
  })
  status: SubscriptionStatus

  @Column({ type: "smallint", default: 0, comment: "0: Not sent, 1: Sent" })
  is_expiry_email_send: number

  @ManyToOne(() => Company)
  @JoinColumn({ name: "company_id" })
  company: Company

  @BeforeInsert()
  @BeforeUpdate()
  calculateEndDate() {
    if (this.subscription_start_date && this.duration && this.duration_type) {
      const startDate = new Date(this.subscription_start_date)

      if (this.duration_type === DurationType.MONTHS) {
        startDate.setMonth(startDate.getMonth() + this.duration)
      } else if (this.duration_type === DurationType.YEARS) {
        startDate.setFullYear(startDate.getFullYear() + this.duration)
      } else if (this.duration_type === DurationType.DAYS) {
        startDate.setDate(startDate.getDate() + this.duration)
      }

      this.subscription_end_date = startDate
    }
  }
}
