import { Injectable, Logger, ConflictException, BadRequestException } from '@nestjs/common';
import { User, UserEntity } from '../entities/User';
import { v4 as uuidv4 } from 'uuid';
import * as bcrypt from 'bcrypt';
import { MailService } from '../../core/mail/MailService';
import db from '../../config/database';

@Injectable()
export class RegistrationService {
  private readonly logger = new Logger(RegistrationService.name);
  private readonly mailService: MailService;

  constructor() {
    this.mailService = MailService.getInstance();
  }

  async register(
    username: string,
    email: string,
    password: string,
    companyName: string,
    phone: string,
    businessType: string,
  ): Promise<{ userId: string; verificationToken: string }> {
    try {
      const existingUser = await db('cf_user')
        .where('username', username)
        .orWhere('email', email)
        .first();

      if (existingUser) {
        if (existingUser.username === username) {
          throw new ConflictException('Username already exists');
        } else {
          throw new ConflictException('Email already exists');
        }
      }

      const hashedPassword = await bcrypt.hash(password, 10);
      const verificationToken = uuidv4();
      const userId = uuidv4();

      await db('cf_user').insert({
        id: userId,
        username,
        email,
        passwordHash: hashedPassword,
        companyName,
        phone,
        businessType,
        role: 'OPERATOR',
        status: 'active',
        tenantId: `tenant-${userId}`,
        createdAt: new Date(),
        updatedAt: new Date()
      });

      await this.mailService.sendWelcomeEmail(email, username);

      this.logger.log(`Registered new user: ${username} (${email})`);
      return { userId, verificationToken };
    } catch (error) {
      this.logger.error('Failed to register user', error);
      throw error;
    }
  }

  async verifyEmail(token: string): Promise<boolean> {
    this.logger.log(`Email verification requested with token: ${token}`);
    return true;
  }

  async resendVerificationEmail(email: string): Promise<boolean> {
    await this.mailService.sendMail({
      to: email,
      subject: 'Email Verification',
      text: 'Please verify your email address.'
    });
    return true;
  }

  async getUserInfo(userId: string): Promise<User | null> {
    const user = await db('cf_user').where('id', userId).first();
    if (!user) {
      return null;
    }
    return UserEntity.create(user);
  }
}
