import { Injectable, BadRequestException, UnauthorizedException, Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
import { UserService } from './user.service';
import { OtpService } from './otp.service';
import { SessionService } from './session.service';
import { LoginHistoryService } from './login-history.service';
import { EmailService } from './email.service';
import { PasswordUtis } from 'src/common/utils/utils.password';
import { RegisterDto, LoginDto, RequestOtpDto, VerifyOtpDto } from '../dtos';
import { JwtPayload, OtpType } from '../types/auth.types';
import { PaymentService } from 'src/modules/payment/payment.service';

@Injectable()
export class AuthService {
    private readonly logger = new Logger(AuthService.name)
    constructor(
        private readonly userService: UserService,
        private readonly otpService: OtpService,
        private readonly sessionService: SessionService,
        private readonly loginHistoryService: LoginHistoryService,
        private readonly emailService: EmailService,
        private readonly jwtService: JwtService,
        private readonly configService: ConfigService,
        private readonly paymentService: PaymentService,
    ) { }

    async register(dto: RegisterDto) {

        if (dto.password !== dto.passwordConfirm) {
            throw new BadRequestException('Passwords do not match');
        }

        const profile = dto.fullName || dto.ktpNo || dto.batchYear != null
            ? {
                fullName: dto.fullName,
                gender: dto.gender,
                ktpNo: dto.ktpNo,
                batchYear: dto.batchYear,
                entryClass: dto.entryClass,
                graduationClass: dto.graduationClass,
                academicEntryYear: dto.academicEntryYear,
                academicExitYear: dto.academicExitYear,
                graduationYear: dto.graduationYear,
            }
            : undefined;


        const user = await this.userService.createUser({
            username: dto.username,
            email: dto.email,
            password: dto.password,
            phoneNumber: dto.phoneNumber,
            profile,
        });

        await this.emailService.sendWelcomeEmail(user.email, user.username);
        return {
            id: user.id,
            username: user.username,
            email: user.email,
        };
    }


    async requestOtp(requestOtpDto: RequestOtpDto) {
        const user = await this.userService.findByEmail(requestOtpDto.email);
        if (!user) {
            throw new BadRequestException('User not found');
        }
        if (!user.isActive) {
            throw new BadRequestException('User account is inactive');
        }
        const otp = await this.otpService.generateOtp({
            userId: user.id,
            email: user.email,
            otpType: 'REGISTER' as OtpType,
            phoneNumber: user.phoneNumber || "",
        });

        await this.emailService.sendOtpEmail(user.email, otp.otpCode);

        await this.loginHistoryService.createLoginHistory({
            userId: user.id,
            username: user.username,
            loginStatus: 'OTP_SENT',
        });

        return {
            message: 'OTP sent to your email',
            email: user.email,
            expiresIn: 300,
        };
    }

    async verifyOtp(verifyOtpDto: VerifyOtpDto) {
        const user = await this.userService.findByEmail(verifyOtpDto.email);
        if (!user) {
            throw new BadRequestException('User not found');
        }
        if (!user.isActive) {
            throw new BadRequestException('User account is inactive');
        }
        try {
            await this.otpService.verifyOtp({
                userId: user.id,
                email: user.email,
                otpCode: verifyOtpDto.otpCode,
                otpType: "REGISTER" as OtpType,
            });

            return await this.handlePostAuthLogin(user);
        } catch (error) {
            await this.loginHistoryService.createLoginHistory({
                userId: user.id,
                username: user.username,
                loginStatus: 'FAILED',
                failedReason: error.message,
            });

            throw error;
        }
    }

    async login(loginDto: LoginDto) {
        const user = await this.userService.findByUsernameOrEmail(
            loginDto.username,
            loginDto.email,
        );

        if (!user) {
            const identifier = loginDto.username || loginDto.email || 'unknown';
            await this.loginHistoryService.createLoginHistory({
                userId: 'unknown',
                username: identifier,
                loginStatus: 'FAILED',
                failedReason: 'User not found',
            });

            throw new BadRequestException('Invalid credentials');
            // throw new BadRequestException('Invalid credentials');
        }

        if (!user.isActive) {
            await this.loginHistoryService.createLoginHistory({
                userId: user.id,
                username: user.username,
                loginStatus: 'FAILED',
                failedReason: 'Account is inactive',
            });

            throw new BadRequestException('User account is inactive');
        }
        const isPasswordValid = await PasswordUtis.commparePassword(
            loginDto.password,
            user.password,
        );


        if (!isPasswordValid) {
            await this.loginHistoryService.createLoginHistory({
                userId: user.id,
                username: user.username,
                loginStatus: 'FAILED',
                failedReason: 'Invalid password',
            });

            throw new UnauthorizedException('Invalid credentials');
        }

        return await this.handlePostAuthLogin(user);
    }

    async logout(token: string): Promise<void> {
        await this.sessionService.invalidateSession(token);
    }

    async logoutAllDevices(userId: string): Promise<void> {
        await this.sessionService.invalidateAllUserSessions(userId);
    }

    async validateToken(token: string) {
        try {
            const session = await this.sessionService.findSessionByToken(token);

            if (!session) {
                throw new UnauthorizedException('Invalid token');
            }

            const decoded = this.jwtService.verify<JwtPayload>(token);
            return decoded;
        } catch (error) {
            throw new UnauthorizedException('Invalid token');
        }
    }

    private async handlePostAuthLogin(user: any) {
        const { needsPayment, payment } = await this.paymentService.getRegistrationStatus(user.username);

        if (needsPayment) {
            await this.paymentService.findOrCreateRegistrationPayment(user.id, user.username);
        }

        const { accessToken, refreshToken } = await this.generateTokens(user);

        await this.sessionService.createSession({
            userId: user.id,
            token: accessToken,
            createdBy: user.username,
        });

        await this.loginHistoryService.createLoginHistory({
            userId: user.id,
            username: user.username,
            loginStatus: 'SUCCESS',
        });

        await this.userService.updateLastLogin(user.id);

        const paymentInfo = needsPayment ? this.paymentService.getPaymentInfo() : null;

        return {
            user: {
                id: user.id,
                username: user.username,
                email: user.email,
                isActive: user.isActive,
            },
            accessToken,
            refreshToken,
            needsPayment,
            paymentInfo,
        };
    }

    private async generateTokens(user: any) {
        const userWithRoles = await this.userService.getUserWithRoles(user.id);
        const roles = userWithRoles?.userRoleMappings?.map((urm) => urm.role.roleName) || [];
        const payload: JwtPayload = {
            id: user.id,
            username: user.username,
            email: user.email,
            roles,
        };

        const accessToken = this.jwtService.sign(payload, {
            secret: this.configService.get<string>('JWT_SECRET'),
            expiresIn: '24h',
        });

        const refreshToken = this.jwtService.sign(payload, {
            secret: this.configService.get<string>('JWT_REFRESH_SECRET'),
            expiresIn: '7d',
        });

        return { accessToken, refreshToken };
    }
}
