import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { PasswordUtis } from 'src/common/utils/utils.password';
import type { User } from 'generated/prisma/client';

@Injectable()
export class UserService {
    constructor(private readonly prismaService: PrismaService) { }

    /**
     * Create a new user
     */
    async createUser(data: {
        username: string;
        email: string;
        password: string;
        phoneNumber?: string;
        createdBy?: string;
        profile?: {
            fullName?: string;
            identificationNo?: string;
            gender?: number;
            batchYear?: number;
            entryClass?: string;
            graduationClass?: string;
            academicEntryYear?: number;
            academicExitYear?: number;
            graduationYear?: number;
        };
    }): Promise<User> {
        const existingUser = await this.findByUsernameOrEmail(
            data.username,
            data.email,
        );

        if (existingUser) {
            throw new BadRequestException(`User with username or email already exists`);
        }

        const hashedPassword = await PasswordUtis.hashPassword(data.password);
        return this.prismaService.$transaction(async (tx) => {
            const user = await tx.user.create({
                data: {
                    username: data.username,
                    email: data.email,
                    password: hashedPassword,
                    phoneNumber: data.phoneNumber,
                    createdBy: data.createdBy,
                },
            });

            if (data.profile) {
                await tx.userProfile.create({
                    data: {
                        userId: user.id,
                        fullName: data.profile.fullName,
                        identificationNo: data.profile.identificationNo,
                        batchYear: data.profile.batchYear ?? new Date().getFullYear(),
                        entryClass: data.profile.entryClass,
                        graduationClass: data.profile.graduationClass,
                        academicEntryYear: data.profile.academicEntryYear,
                        academicExitYear: data.profile.academicExitYear,
                        graduationYear: data.profile.graduationYear,
                    },
                });
            }
            return user;
        });
    }

    /**
     * Find user by ID
     */
    async findById(id: string): Promise<User> {
        const user = await this.prismaService.user.findUnique({
            where: { id },
        });

        if (!user) {
            throw new NotFoundException(`User with ID ${id} not found`);
        }

        return user;
    }

    /**
     * Find user by username or email
     */
    async findByUsernameOrEmail(
        username?: string,
        email?: string,
    ): Promise<User | null> {
        if (!username && !email) {
            return null;
        }

        return this.prismaService.user.findFirst({
            where: {
                OR: [
                    ...(username ? [{ username }] : []),
                    ...(email ? [{ email }] : []),
                ],
            },
        });
    }

    /**
     * Find user by username
     */
    async findByUsername(username: string): Promise<User | null> {
        return this.prismaService.user.findUnique({
            where: { username },
        });
    }

    /**
     * Find user by email
     */
    async findByEmail(email: string): Promise<User | null> {
        return this.prismaService.user.findUnique({
            where: { email },
        });
    }

    /**
     * Verify user password
     */
    async verifyPassword(userId: string, password: string): Promise<boolean> {
        const user = await this.findById(userId);
        return PasswordUtis.commparePassword(password, user.password);
    }

    /**
     * Update user last login
     */
    async updateLastLogin(userId: string): Promise<void> {
        await this.prismaService.user.update({
            where: { id: userId },
            data: { updatedBy: userId },
        });
    }

    /**
     * Get user with roles
     */
    async getUserWithRoles(userId: string) {
        return this.prismaService.user.findUnique({
            where: { id: userId },
            include: {
                userRoleMappings: {
                    include: {
                        role: true,
                    },
                },
            },
        });
    }

    /**
     * Deactivate user
     */
    async deactivateUser(userId: string, deactivatedBy: string): Promise<void> {
        await this.prismaService.user.update({
            where: { id: userId },
            data: {
                isActive: false,
                updatedBy: deactivatedBy,
            },
        });
    }
}
