import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { EmailTokens } from './entities/email_tokens.entity';

@Injectable()
export class EmailTokensService {
  constructor(
    @InjectRepository(EmailTokens)
    private readonly tokenRepository: Repository<EmailTokens>,
  ) {}

  /**
   * Create email token
   */
  async createToken(data: {
    token: string;
    token_type: string;
    reference_id: number;
    user_id: number;
    expires_at: Date;
  }) {
    const token = this.tokenRepository.create(data);
    return await this.tokenRepository.save(token);
  }

  /**
   * Validate token
   */
  async validateToken(token: string) {
    const tokenRecord = await this.tokenRepository.findOne({
      where: { token },
    });

    if (!tokenRecord) {
      return { valid: false, error: 'Token not found' };
    }

    if (tokenRecord.status === 'used') {
      return { valid: false, error: 'Token already used' };
    }

    if (
      tokenRecord.status === 'expired' ||
      new Date() > tokenRecord.expires_at
    ) {
      return { valid: false, error: 'Token expired' };
    }

    return { valid: true, tokenRecord };
  }

  /**
   * Mark token as used
   */
  async markAsUsed(token: string) {
    await this.tokenRepository.update({ token }, { status: 'used' });
  }
}
