import {
  IsEmail,
  IsInt,
  IsNotEmpty,
  IsOptional,
  IsPhoneNumber,

  IsPositive,

  IsString
} from "class-validator";
import { BeforeInsert, BeforeUpdate, Column, Entity, OneToMany, PrimaryGeneratedColumn } from "typeorm";
import { config } from '../../config';
import { ResponseGroupContact } from '../responses/ResponseGroupContact';
import { Address } from "./Address";
import type { RunnerGroup } from "./RunnerGroup";

/**
 * Defines the GroupContact entity.
 * Mainly it's own class to reduce duplicate code and enable contact's to be associated with multiple groups.
*/
@Entity()
export class GroupContact {
  /**
   * Autogenerated unique id (primary key).
   */
  @PrimaryGeneratedColumn()
  @IsInt()
  id: number;

  /**
   * The contact's first name.
   */
  @Column()
  @IsNotEmpty()
  @IsString()
  firstname: string;

  /**
   * The contact's middle name.
   */
  @Column({ nullable: true })
  @IsOptional()
  @IsString()
  middlename?: string;

  /**
   * The contact's last name.
   */
  @Column()
  @IsNotEmpty()
  @IsString()
  lastname: string;

  /**
   * The contact's address.
   * This is a address object to prevent any formatting differences.
   */
  @Column(type => Address)
  address?: Address;

  /**
   * The contact's phone number.
   * This will be validated against the configured country phone numer syntax (default: international).
   */
  @Column({ nullable: true })
  @IsOptional()
  @IsPhoneNumber(config.phone_validation_countrycode)
  phone?: string;

  /**
   * The contact's email address.
   * Could later be used to automaticly send mails concerning the contact's associated groups.
   */
  @Column({ nullable: true })
  @IsOptional()
  @IsEmail()
  email?: string;

  /**
    * Used to link contacts to groups.
    */
  @OneToMany(() => require("./RunnerGroup").RunnerGroup, (group: RunnerGroup) => group.contact, { nullable: true })
  groups!: RunnerGroup[];

  @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(): ResponseGroupContact {
    return new ResponseGroupContact(this);
  }
}