import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { CreateNotificationDto, UpdateNotificationDto, QueryNotificationDto } from './dto';

@Injectable()
export class NotificationService {
    private readonly logger = new Logger(NotificationService.name);

    constructor(private readonly prisma: PrismaService) { }

    async create(dto: CreateNotificationDto, createdBy: string) {
        return this.prisma.notification.create({
            data: {
                userId: dto.userId || null,
                isFromSystem: dto.isFromSystem ?? 0,
                title: dto.title,
                description: dto.description,
                createdBy,
            },
        });
    }

    async findAll(query: QueryNotificationDto) {
        const page = query.page || 1;
        const limit = query.limit || 10;
        const skip = (page - 1) * limit;

        const where: Record<string, any> = {
            deleteStatus: 0,
        };

        if (query.isFromSystem !== undefined) {
            where.isFromSystem = query.isFromSystem;
        }

        const [items, total] = await this.prisma.$transaction([
            this.prisma.notification.findMany({
                where,
                include: { user: { select: { id: true, username: true, email: true, profile: { select: { id: true } } } } },
                skip,
                take: limit,
                orderBy: { createdAt: 'desc' },
            }),
            this.prisma.notification.count({ where }),
        ]);

        return { items, total, page, limit };
    }

    async findByUser(userId: string, query: QueryNotificationDto) {
        const page = query.page || 1;
        const limit = query.limit || 10;
        const skip = (page - 1) * limit;

        const where: Record<string, any> = {
            deleteStatus: 0,
            OR: [
                { userId },
                { userId: null },
            ],
        };

        if (query.isFromSystem !== undefined) {
            where.isFromSystem = query.isFromSystem;
        }

        const [items, total] = await this.prisma.$transaction([
            this.prisma.notification.findMany({
                where,
                skip,
                take: limit,
                orderBy: { createdAt: 'desc' },
            }),
            this.prisma.notification.count({ where }),
        ]);

        return { items, total, page, limit };
    }

    async findOne(id: string) {
        const notification = await this.prisma.notification.findUnique({
            where: { id },
            include: { user: { select: { id: true, username: true, email: true } } },
        });

        if (!notification || notification.deleteStatus === 1) {
            throw new NotFoundException('Notification not found');
        }

        return notification;
    }

    async update(id: string, dto: UpdateNotificationDto) {
        await this.findOne(id);

        return this.prisma.notification.update({
            where: { id },
            data: dto,
        });
    }

    async softDelete(id: string) {
        await this.findOne(id);

        return this.prisma.notification.update({
            where: { id },
            data: { deleteStatus: 1 },
        });
    }

    async hardDelete(id: string) {
        await this.findOne(id);

        return this.prisma.notification.delete({
            where: { id },
        });
    }
}
