import { BadRequestException, Injectable, Logger, NotFoundException } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';

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

    constructor(private readonly prisma: PrismaService) { }

    async getPayments(status?: string) {
        const where: Record<string, any> = { paymentType: 'REGISTRATION' };
        if (status) where.status = status;

        return this.prisma.payment.findMany({
            where,
            include: { attachment: true, user: { include: { profile: true } } },
            orderBy: { createdAt: 'desc' },
        });
    }

    async confirmPayment(paymentId: string, adminUsername: string) {
        const payment = await this.prisma.payment.findUnique({
            where: { id: paymentId },
        });

        if (!payment) {
            throw new NotFoundException('Payment not found');
        }

        if (payment.status === 'PAID') {
            throw new BadRequestException('Payment is already confirmed');
        }

        if (payment.status !== 'WAITING_PAYMENT') {
            throw new BadRequestException('Payment is not in waiting for payment status');
        }

        return this.prisma.payment.update({
            where: { id: paymentId },
            data: {
                status: 'PAID',
                updatedBy: adminUsername,
            },
        });
    }

    async rejectPayment(paymentId: string, adminUsername: string) {
        const payment = await this.prisma.payment.findUnique({
            where: { id: paymentId },
        });

        if (!payment) {
            throw new NotFoundException('Payment not found');
        }

        if (payment.status === 'PAID' || payment.status === 'CANCELLED') {
            throw new BadRequestException('Cannot reject a paid or cancelled payment');
        }

        return this.prisma.payment.update({
            where: { id: paymentId },
            data: {
                status: 'CANCELLED',
                updatedBy: adminUsername,
            },
        });
    }

    async getRoles() {
        return this.prisma.userRole.findMany({
            where: { isActive: true },
            orderBy: { roleName: 'asc' },
        });
    }

    async getMenus() {
        return this.prisma.navbarMenu.findMany({
            where: { isActive: true },
            include: { children: true },
            orderBy: { sortOrder: 'asc' },
        });
    }

    async getRoleMenus(roleId: string) {
        const role = await this.prisma.userRole.findUnique({ where: { id: roleId } });
        if (!role) throw new NotFoundException('Role not found');

        return this.prisma.roleMenuMapping.findMany({
            where: { roleId },
            include: { menu: true },
        });
    }

    async assignMenuToRole(roleId: string, menuId: string) {
        const role = await this.prisma.userRole.findUnique({ where: { id: roleId } });
        if (!role) throw new NotFoundException('Role not found');

        const menu = await this.prisma.navbarMenu.findUnique({ where: { id: menuId } });
        if (!menu) throw new NotFoundException('Menu not found');

        const existing = await this.prisma.roleMenuMapping.findUnique({
            where: { roleId_menuId: { roleId, menuId } },
        });
        if (existing) throw new BadRequestException('Menu already assigned to this role');

        return this.prisma.roleMenuMapping.create({
            data: { roleId, menuId },
            include: { role: true, menu: true },
        });
    }

    async removeMenuFromRole(roleId: string, menuId: string) {
        const mapping = await this.prisma.roleMenuMapping.findUnique({
            where: { roleId_menuId: { roleId, menuId } },
        });
        if (!mapping) throw new NotFoundException('Menu assignment not found');

        await this.prisma.roleMenuMapping.delete({
            where: { id: mapping.id },
        });
    }
}
