import {
  CreateDateColumn,
  UpdateDateColumn,
  DeleteDateColumn,
  Entity,
  Index,
  Column,
  RelationId,
  ManyToOne,
  PrimaryGeneratedColumn,
  VersionColumn
} from 'typeorm'
import { ObjectType, Field, Int, ID, registerEnumType } from 'type-graphql'

import { Domain } from '@things-factory/shell'
import { User } from '@things-factory/auth-base'
import { OrgMemberTargetType, OrgMemberTarget } from '@things-factory/organization'

export enum NotificationRuleStatus {
  DRAFT = 'DRAFT',
  RELEASED = 'RELEASED'
}

registerEnumType(NotificationRuleStatus, {
  name: 'NotificationRuleStatus',
  description: 'state enumeration of a notificationRule'
})

@ObjectType()
export class RecipientItem {
  @Field(type => OrgMemberTargetType, { nullable: true })
  type?: OrgMemberTargetType

  @Field({ nullable: true })
  value?: string

  @Field(type => OrgMemberTarget, { nullable: true })
  recipient?: OrgMemberTarget
}

@Entity()
@Index(
  'ix_notification_rule_0',
  (notificationRule: NotificationRule) => [notificationRule.domain, notificationRule.name, notificationRule.deletedAt],
  { unique: true }
)
@ObjectType({ description: 'Entity for NotificationRule' })
export class NotificationRule {
  @PrimaryGeneratedColumn('uuid')
  @Field(type => ID)
  readonly id: string

  @VersionColumn()
  @Field({ nullable: true })
  version?: number = 1

  @ManyToOne(type => Domain)
  @Field(type => Domain)
  domain?: Domain

  @RelationId((notificationRule: NotificationRule) => notificationRule.domain)
  domainId?: string

  @Column()
  @Field({ nullable: true })
  name?: string

  @Column({ nullable: true })
  @Field({ nullable: true })
  description?: string

  @Column({ nullable: true })
  @Field({ nullable: true })
  state?: NotificationRuleStatus

  @Column({ nullable: true })
  @Field({ nullable: true })
  title: string

  @Column({ nullable: true })
  @Field({ nullable: true })
  body: string

  @Column({ nullable: true })
  @Field({ nullable: true })
  url: string

  @Column({ nullable: true })
  @Field({ nullable: true })
  thumbnail: string

  @Column({ nullable: true })
  @Field({ nullable: true })
  channels: string

  @Column('simple-json', { nullable: true })
  @Field(type => [RecipientItem], { nullable: true, description: 'notification recipients.' })
  recipients: string

  @CreateDateColumn()
  @Field({ nullable: true })
  createdAt?: Date

  @UpdateDateColumn()
  @Field({ nullable: true })
  updatedAt?: Date

  @DeleteDateColumn()
  @Field({ nullable: true })
  deletedAt?: Date

  @ManyToOne(type => User, { nullable: true })
  @Field(type => User, { nullable: true })
  creator?: User

  @RelationId((notificationRule: NotificationRule) => notificationRule.creator)
  creatorId?: string

  @ManyToOne(type => User, { nullable: true })
  @Field(type => User, { nullable: true })
  updater?: User

  @RelationId((notificationRule: NotificationRule) => notificationRule.updater)
  updaterId?: string
}
