import { ExceptionFilter, Injectable, Logger, NotFoundException, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from 'src/prisma/prisma.service';
import * as bcrypt from 'bcrypt';
import { AuthEntity } from './entity/auth.entity';

@Injectable()
export class AuthService {
	constructor(
		private prisma: PrismaService,
		private jwtService: JwtService
	) {}
	private logger = new Logger(AuthService.name);
	async login(email: string, password: string): Promise<AuthEntity> {
		const user = await this.prisma.user.findUnique({ where: { email } });

		if (!user) {
			// this.logger.log({ level: 'info', message: `No user found for email: ${email}`, refCode: '11402' });
			throw new NotFoundException(`No user found for email: ${email}`);
		}

		if (!user.active) {
			// this.logger.log({ level: 'info', message: `User is not active`, refCode: '11402' });
			throw new UnauthorizedException('User is not active');
		}

		const isPasswordValid = await bcrypt.compare(password, user.password);

		if (!isPasswordValid) {
			// this.logger.log({ level: 'info', message: 'Invalid password', refCode: '11402' });
			throw new UnauthorizedException('Invalid password');
		}
		var safeUser: any = { ...user };
		delete safeUser.password;
		// this.logger.log({ level: 'info', message: 'User logged in', refCode: '11200' });
		return {
			accessToken: this.jwtService.sign({ userId: user.id }),
			user: safeUser,
		};
	}

	async validateToken(email: string, token: string) {
		const user = await this.prisma.user.findUnique({ where: { email: email } });

		if (!user) {
			// this.logger.log({ level: 'info', message: `Invalid email with ${email}`, refCode: '11402' });
			throw new UnauthorizedException('Invalid email');
		}

		try {
			const isTokenValid = this.jwtService.verify(token);

			if (!isTokenValid) {
				// this.logger.log({ level: 'info', message: 'Invalid token', refCode: '11402' });
				throw new UnauthorizedException('Invalid token');
			}
		} catch (error) {
			// this.logger.log({ level: 'info', message: 'Invalid token', refCode: '11402' });
			throw new UnauthorizedException('Invalid token');
		}

		// this.logger.log({ level: 'info', message: 'Token is valid', refCode: '11200' });
		return { responsecode: 200, message: 'token is valid' };
	}
}
