import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { Company } from '../../companies/entities/company.entity';
import { User } from '../../user/entities/user.entity';

/**
 * CLIENT ACCESS TOKEN ENTITY
 * 
 * Stores invitation tokens sent to clients via email/WhatsApp
 * When client clicks the link, they use this token to access login page
 * 
 * Lifecycle:
 * 1. Coordinator clicks [Invite Client]
 * 2. System creates new ClientAccessToken (is_used=0)
 * 3. Token sent via email + WhatsApp
 * 4. Client clicks link → /client/login/:token
 * 5. Client enters email & phone → System checks this table
 * 6. If valid & not expired & not used → Allow OTP login
 * 7. After first OTP verification → Mark token as used (is_used=1)
 */
@Entity('client_access_tokens')
@Index(['token'], { unique: true })
@Index(['company_id', 'client_email'])
@Index(['expires_at'])
export class ClientAccessToken {
  @PrimaryGeneratedColumn()
  id: number;

  /**
   * Unique token (random UUID)
   * Used in invite link: /client/login/TOKEN_HERE
   */
  @Column({ type: 'varchar', length: 255, unique: true })
  token: string;

  /**
   * Company being invited
   */
  @Column()
  company_id: number;

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

  /**
   * Client's email address
   */
  @Column({ type: 'varchar', length: 255 })
  client_email: string;

  /**
   * Client's phone number (E.164 format: +971501234567)
   */
  @Column({ type: 'varchar', length: 20 })
  client_phone: string;

  /**
   * Who created this invite (Coordinator user_id)
   */
  @Column()
  created_by_user_id: number;

  @ManyToOne(() => User)
  @JoinColumn({ name: 'created_by_user_id' })
  created_by_user: User;

  /**
   * Has this token been used (0 = not used, 1 = used)
   * Once used for login, set to 1 to prevent reuse
   */
  @Column({ default: 0 })
  is_used: number;

  /**
   * When was this token used for login
   * Null until first use
   */
  @Column({ type: 'datetime', nullable: true })
  used_at: Date;

  /**
   * When does this token expire (7 days from creation)
   * After expiry, link should not work
   */
  @Column({ type: 'datetime' })
  expires_at: Date;

  /**
   * Timestamp tracking
   */
  @CreateDateColumn()
  created_at: Date;

  @UpdateDateColumn()
  updated_at: Date;

  /**
   * Helper method: Is token still valid?
   */
  isValid(): boolean {
    return (
      this.is_used === 0 &&
      new Date() <= this.expires_at
    );
  }

  /**
   * Helper method: Is token expired?
   */
  isExpired(): boolean {
    return new Date() > this.expires_at;
  }
}
