import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  UpdateDateColumn,
  JoinColumn,
  OneToOne,
  ManyToOne,
} from "typeorm";
import { bigintTransformer } from "../common/entity";
import { User } from "./user.entity";

@Entity({ name: "licenses" })
export class License {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ nullable: true, type: "datetime" })
  expiry_date: Date | null;

  @Column()
  account_id: number;

  @Column()
  type: string;

  @Column()
  status: string;

  @Column({ nullable: true, type: "bigint", transformer: bigintTransformer })
  allocated_user_id: number | null;

  @Column({ nullable: true, type: "bigint", transformer: bigintTransformer })
  order_id: number | null;

  @Column({ nullable: true, type: "datetime" })
  deleted_at: Date | null;

  @Column({ nullable: true, type: "bigint", transformer: bigintTransformer })
  delete_order_id: number | null;

  @Column({ nullable: true, type: "datetime" })
  created_by: string | null;

  @CreateDateColumn({
    default: () => "datetime('now', 'localtime')",
    type: "datetime",
  })
  created_at: Date;

  @Column({ nullable: true, type: "datetime" })
  updated_by: string | null;

  @UpdateDateColumn({
    default: () => "datetime('now', 'localtime')",
    type: "datetime",
  })
  updated_at: Date;

  @OneToOne(() => User, (user) => user.license)
  @JoinColumn({ name: "allocated_user_id" })
  user: User | null;
}

@Entity({ name: "license_allocation_history" })
export class LicenseAllocationHistory {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  user_id: number;

  @Column()
  license_id: number;

  @Column()
  is_allocated: boolean;

  @Column()
  account_id: number;

  @Column()
  executed_at: Date;

  @Column()
  switch_from_type: string;

  @Column({ nullable: true, type: "datetime" })
  deleted_at: Date | null;

  @Column({ nullable: true, type: "datetime" })
  created_by: string | null;

  @CreateDateColumn({
    default: () => "datetime('now', 'localtime')",
    type: "datetime",
  })
  created_at: Date;

  @Column({ nullable: true, type: "datetime" })
  updated_by: string | null;

  @UpdateDateColumn({
    default: () => "datetime('now', 'localtime')",
    type: "datetime",
  })
  updated_at: Date;

  @ManyToOne(() => License, (licenses) => licenses.id, {
    createForeignKeyConstraints: false,
  }) // createForeignKeyConstraintsはSQLite用設定値.本番用は別途migrationで設定
  @JoinColumn({ name: "license_id" })
  license: License | null;
}
