import { json, error } from '@sveltejs/kit';
import { PaymentValidator } from '$lib/server/services/PaymentValidator';
import prisma from '$lib/server/prisma';
import dotenv from 'dotenv';
import nodemailer from 'nodemailer';

dotenv.config();

export const POST = async ({ request, url }) => {
	console.log('Subscription notification received:', request.headers);

	try {
		const payload = await request.json();
		console.log('Subscription payment payload:', payload);

		const validatedPayload = PaymentValidator.validateCallback(payload);

		if (validatedPayload?.status === 'settled') {
			return await processSubscriptionPayment(validatedPayload, url);
		}

		return json({ message: 'Subscription notification acknowledged' });
	} catch (e) {
		console.error('Subscription payment webhook error:', e);
		return json({ error: e.message || 'Internal server error' }, { status: 500 });
	}
};

async function processSubscriptionPayment(payload, url) {
	return await prisma.$transaction(
		async (tx) => {
			if (!payload.client_invoice_ref?.startsWith('SUB-')) {
				throw error(400, 'Invalid subscription payment reference');
			}

			const refParts = payload.client_invoice_ref.split('-');
			const userId = parseInt(refParts[2]);
			const planId = parseInt(refParts[3]);

			if (!userId || !planId) throw error(400, 'Invalid reference format');

			const user = await tx.user.findUnique({ where: { id: userId } });
			const plan = await tx.subscriptionPlan.findUnique({ where: { id: planId } });
			if (!user || !plan) throw error(404, 'User or plan not found');

			const existingSubscription = await tx.userSubscription.findFirst({
				where: { userId, isActive: true, status: 'ACTIVE', endsAt: { gte: new Date() } }
			});
			if (existingSubscription) throw error(400, 'User already has an active subscription');

			const planPrice = Number(plan.price);
			const paidAmount = parseFloat(payload.amount_paid || '0');
			const expectedAmount = planPrice;
			if (Math.abs(paidAmount - expectedAmount) > 1)
				console.warn(`Payment mismatch: expected ${expectedAmount}, got ${paidAmount}`);

			const subscription = await tx.userSubscription.create({
				data: {
					userId,
					planId,
					status: 'ACTIVE',
					isActive: true,
					startsAt: new Date(),
					endsAt: new Date(Date.now() + plan.duration * 24 * 60 * 60 * 1000)
				},
				include: { plan: true }
			});

			const payment = await tx.payment.create({
				data: {
					userId,
					subscriptionId: subscription.id,
					amount: paidAmount,
					status: 'SUCCEEDED',
					provider: 'PESAFLOW',
					providerRef: payload.payment_reference?.[0]?.payment_reference || payload.client_invoice_ref,
					currency: payload.currency || 'KES',
					rawPayload: payload
				}
			});

			// 📧 Set up Nodemailer Transporter
			const transporter = nodemailer.createTransport({
				host: process.env.MAIL_HOST,
				port: Number(process.env.MAIL_PORT),
				secure: false,
				auth: {
					user: process.env.MAIL_USER,
					pass: process.env.MAIL_PASS
				}
			});

			// 🧾 Prepare Email Templates
			const userHtml = `
				<div style="font-family: Arial, sans-serif; background:#f4f4f4; padding:20px;">
					<div style="max-width:600px;margin:0 auto;background:#fff;padding:30px;border-radius:10px;">
					    <img src="${url.origin}/kLawLogo.png" alt="Kenya Law Logo" style="max-width:150px; margin-bottom:20px;" />

						<h2 style="color:#8f2a2b;text-align:center;">Subscription Activated!</h2>
						<p>Dear ${user.name || user.email},</p>
						<p>Your subscription to <strong>Kenya Law</strong> has been successfully activated.</p>

						<div style="background:#f8f9fa;padding:15px;border-radius:8px;margin:20px 0;border-left:4px solid #8f2a2b;">
							<h3 style="margin:0 0 10px 0;color:#8f2a2b;">${plan.name}</h3>
							<p>${plan.description || ''}</p>
							<p style="color:#faa21b;font-weight:bold;">KES ${plan.price}/month</p>
						</div>

						<div style="background:#e8f5e8;padding:15px;border-radius:6px;margin:20px 0;">
							<h4>Payment Details</h4>
							<p><strong>Amount:</strong> KES ${paidAmount}</p>
							<p><strong>Reference:</strong> ${payload.client_invoice_ref}</p>
							<p><strong>Date:</strong> ${payload.payment_date}</p>
							<p><strong>Channel:</strong> ${payload.payment_channel}</p>
						</div>

						<p style="text-align:center;">
							<a href="${url.origin}/legislation" style="background:#8f2a2b;color:white;padding:12px 18px;border-radius:5px;text-decoration:none;">Start Browsing Legislation</a>
						</p>

						<hr style="border:none;border-top:1px solid #ddd;margin:25px 0;" />
						<p style="font-size:12px;color:#666;text-align:center;">
							This is an automated email from the Kenya Law system.<br/>
							Sent on: ${new Date().toLocaleString()}<br/>
							© 2025 National Council for Law Reporting (Kenya Law)
						</p>
					</div>
				</div>
			`;

			const adminHtml = `
				<div style="font-family: Arial, sans-serif; background:#f4f4f4; padding:20px;">
					<div style="max-width:600px;margin:0 auto;background:#fff;padding:30px;border-radius:10px;">
					  <img src="${url.origin}/kLawLogo.png" alt="Kenya Law Logo" style="max-width:150px; margin-bottom:20px;" />

						<h2 style="color:#8f2a2b;text-align:center;">New Subscription Activated</h2>
						<p>A new user has subscribed on Kenya Law:</p>

						<ul>
							<li><strong>Name:</strong> ${user.name || 'N/A'}</li>
							<li><strong>Email:</strong> ${user.email}</li>
							<li><strong>Plan:</strong> ${plan.name}</li>
							<li><strong>Amount Paid:</strong> KES ${paidAmount}</li>
							<li><strong>Reference:</strong> ${payload.client_invoice_ref}</li>
							<li><strong>Payment Date:</strong> ${payload.payment_date}</li>
							<li><strong>Channel:</strong> ${payload.payment_channel}</li>
						</ul>

						<p style="font-size:12px;color:#666;text-align:center;margin-top:30px;">
							This is an automated admin notification.<br/>
							${new Date().toLocaleString()}
						</p>
					</div>
				</div>
			`;


			// 📤 Send both emails
			await transporter.sendMail({
				from: `"Kenya Law" <${process.env.MAIL_USER}>`,
				to: user.email,
				subject: 'Subscription Activated - Kenya Law',
				html: userHtml
			});

			console.log(`✅ Subscription confirmation sent → ${user.email}`);

			await transporter.sendMail({
				from: `"Kenya Law" <${process.env.MAIL_USER}>`,
				to: 'hosea.koskei@bsl.co.ke',
				subject: 'New Subscription Activated - Kenya Law',
				html: adminHtml
			});
			console.log('📨 Admin notification sent → admin@bsl.co.ke');

			return json({ success: true, subscription, payment });
		},
		{ timeout: 10000, isolationLevel: 'Serializable' }
	);
}
