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

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

    constructor(
        private readonly prisma: PrismaService,
        private readonly configService: ConfigService,
    ) { }

    getPaymentInfo() {
        return {
            amount: this.configService.get<number>('REGISTRATION_FEE') || 150000,
            bankName: this.configService.get<string>('PAYMENT_BANK_NAME'),
            bankAccount: this.configService.get<string>('PAYMENT_BANK_ACCOUNT'),
            bankHolder: this.configService.get<string>('PAYMENT_BANK_HOLDER'),
            whatsapp: this.configService.get<string>('PAYMENT_WHATSAPP'),
        };
    }

    async getRegistrationStatus(username: string) {
        const payment = await this.prisma.payment.findFirst({
            where: {
                createdBy: username,
                paymentType: 'REGISTRATION',
            },
            include: { attachment: true },
            orderBy: { createdAt: 'desc' },
        });

        if (!payment) {
            return { needsPayment: true, payment: null };
        }

        if (payment.status === 'PAID') {
            return { needsPayment: false, payment };
        }

        return { needsPayment: true, payment };
    }

    async findOrCreateRegistrationPayment(userId: string, username: string) {
        const existing = await this.prisma.payment.findFirst({
            where: {
                createdBy: username,
                paymentType: 'REGISTRATION',
                status: { in: ['PENDING', 'WAITING_PAYMENT'] },
            },
        });

        if (existing) return existing;

        const baseAmount = this.configService.get<number>('REGISTRATION_FEE') || 150000;
        const uniqueCode = Math.floor(100 + Math.random() * 900);

        return this.prisma.payment.create({
            data: {
                paymentType: 'REGISTRATION',
                paymentMethod: 'BANK_TRANSFER' as PaymentMethod,
                baseAmount,
                uniqueCode,
                totalAmount: baseAmount + uniqueCode,
                status: 'PENDING',
                createdBy: username,
            },
        });
    }

    async submitProof(userId: string, username: string, attachmentId: string) {
        const attachment = await this.prisma.paymentAttachment.findUnique({
            where: { id: attachmentId },
        });

        if (!attachment) {
            throw new NotFoundException('Attachment not found');
        }

        const payment = await this.prisma.payment.findFirst({
            where: {
                createdBy: username,
                paymentType: 'REGISTRATION',
                status: { in: ['PENDING', 'WAITING_PAYMENT'] },
            },
            orderBy: { createdAt: 'desc' },
        });

        if (!payment) {
            throw new BadRequestException('No pending registration payment found');
        }

        const updated = await this.prisma.payment.update({
            where: { id: payment.id },
            data: {
                attachmentId: attachment.id,
                status: 'WAITING_PAYMENT',
                updatedBy: username,
            },
            include: { attachment: true },
        });

        return updated;
    }

    async getUserPaymentHistory(username: string) {
        return this.prisma.payment.findMany({
            where: { createdBy: username, paymentType: 'REGISTRATION' },
            include: { attachment: true },
            orderBy: { createdAt: 'desc' },
        });
    }
}
