import { Injectable, ConflictException, NotFoundException, BadRequestException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from '../prisma/prisma.service';
import * as bcrypt from 'bcrypt';
import { CreateUserDto } from '../dto/create-user.dto';
import { ConfigService } from '@nestjs/config';
import { EmailService } from 'src/email/email.service';

@Injectable()
export class AuthService {
  constructor(
    private prisma: PrismaService,
    private jwtService: JwtService, 
    private configService: ConfigService,
    private emailService: EmailService,
  ) {}

  async validateUser(username: string, password: string): Promise<any> {
    const user = await this.prisma.user.findUnique({
      where: { email: username },
    });
    if (user && (await bcrypt.compare(password, user.password))) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      const { password, ...result } = user;
      return result;
    }
    return null;
  }

  async login(user: any) {
    // const payload = { username: user.email, sub: user.id };
    // return {
    //   access_token: this.jwtService.sign(payload),
    // };
    const payload = { username: user.username, sub: user.id };
    console.log(payload);
    return {
      access_token: this.jwtService.sign(payload, {
        secret: this.configService.get<string>('JWT_SECRET'),
      }),
    };
  }

  async createUser(createUserDto: CreateUserDto) {
    const user = await this.prisma.user.create({
      data: {
        ...createUserDto,
        password: await bcrypt.hash(createUserDto.password, 10),
      },
    });

    // Send welcome email
    await this.emailService.sendWelcomeEmail(user.email, user.name);
    return user;
  }

  async requestPasswordReset(email: string) {
    const user = await this.prisma.user.findUnique({ where: { email } });
    if (!user) {
      throw new NotFoundException('User not found');
    }

    const resetToken = this.jwtService.sign(
      { email, userId: user.id },
      { expiresIn: '1h', secret: process.env.JWT_RESET_SECRET },
    );

    await this.emailService.sendPasswordResetEmail(email, resetToken);
    return { message: 'Password reset instructions sent to your email' };
  }

  async resetPassword(token: string, newPassword: string) {
    try {
      const payload = this.jwtService.verify(token, {
        secret: process.env.JWT_RESET_SECRET,
      });

      const hashedPassword = await bcrypt.hash(newPassword, 10);
      await this.prisma.user.update({
        where: { email: payload.email },
        data: { password: hashedPassword },
      });

      return { message: 'Password reset successful' };
    } catch (error) {
     throw new BadRequestException('Invalid or expired reset token');
    }
  }
  async getUserInfo(userId: number) {
    if (!userId) {
      throw new Error('User ID is required');
    }
    
    return this.prisma.user.findUnique({
      where: {
        id: userId,  // Make sure userId is properly passed and converted to number if needed
      },
      select: {
        id: true,
        name: true,
        email: true,
        isAdmin: true
      }
    });
  }
}
