import { fail } from '@sveltejs/kit';
import type { Actions, PageServerLoad } from './$types';
import { supabaseAdmin } from '$lib/server/supabase';
import { sendTemplatedEmail } from '$lib/server/email';
import { logMemberAction } from '$lib/server/audit';

export const load: PageServerLoad = async ({ locals }) => {
	const { session } = await locals.safeGetSession();
	if (!session) return { pendingMembers: [] };

	// Get pending status ID
	const { data: pendingStatus } = await locals.supabase
		.from('membership_statuses')
		.select('id')
		.eq('name', 'pending')
		.single();

	if (!pendingStatus) return { pendingMembers: [] };

	// Load pending members
	const { data: pendingMembers } = await locals.supabase
		.from('members')
		.select(`
			id,
			member_id,
			first_name,
			last_name,
			email,
			phone,
			nationality,
			address,
			date_of_birth,
			created_at
		`)
		.eq('membership_status_id', pendingStatus.id)
		.order('created_at', { ascending: true });

	return {
		pendingMembers: pendingMembers || []
	};
};

export const actions: Actions = {
	approve: async ({ request, locals }) => {
		const { session } = await locals.safeGetSession();
		if (!session) return fail(401, { error: 'Not authenticated' });

		const formData = await request.formData();
		const memberId = formData.get('member_id') as string;

		if (!memberId) return fail(400, { error: 'Missing member ID' });

		// Get active status ID
		const { data: activeStatus } = await supabaseAdmin
			.from('membership_statuses')
			.select('id')
			.eq('name', 'active')
			.single();

		if (!activeStatus) return fail(500, { error: 'Active status not found' });

		// Update member status to active
		const { error } = await supabaseAdmin
			.from('members')
			.update({
				membership_status_id: activeStatus.id,
				approved_at: new Date().toISOString(),
				approved_by: session.user.id
			})
			.eq('id', memberId);

		if (error) return fail(500, { error: 'Failed to approve member' });

		// Get member info for email
		const { data: member } = await supabaseAdmin
			.from('members')
			.select('first_name, email, member_id')
			.eq('id', memberId)
			.single();

		// Send approval email
		if (member) {
			sendTemplatedEmail('member_approved', member.email, {
				first_name: member.first_name,
				member_id: member.member_id || ''
			}, {
				recipientId: memberId,
				recipientName: member.first_name
			});
		}

		// Audit log
		logMemberAction('status_change',
			{ id: session.user.id, email: session.user.email! },
			{ id: memberId, email: member?.email },
			{ old_status: 'pending', new_status: 'active', action: 'approved' }
		);

		return { success: true, approved: member?.first_name };
	},

	reject: async ({ request, locals }) => {
		const { session } = await locals.safeGetSession();
		if (!session) return fail(401, { error: 'Not authenticated' });

		const formData = await request.formData();
		const memberId = formData.get('member_id') as string;
		const reason = formData.get('reason') as string;

		if (!memberId) return fail(400, { error: 'Missing member ID' });

		// Get inactive status ID
		const { data: inactiveStatus } = await supabaseAdmin
			.from('membership_statuses')
			.select('id')
			.eq('name', 'inactive')
			.single();

		if (!inactiveStatus) return fail(500, { error: 'Inactive status not found' });

		// Update member status
		const { error } = await supabaseAdmin
			.from('members')
			.update({
				membership_status_id: inactiveStatus.id,
				rejected_at: new Date().toISOString(),
				rejected_by: session.user.id,
				rejection_reason: reason || null
			})
			.eq('id', memberId);

		if (error) return fail(500, { error: 'Failed to reject member' });

		// Get member info for email
		const { data: member } = await supabaseAdmin
			.from('members')
			.select('first_name, email')
			.eq('id', memberId)
			.single();

		// Send rejection email
		if (member) {
			sendTemplatedEmail('member_rejected', member.email, {
				first_name: member.first_name,
				reason: reason || ''
			}, {
				recipientId: memberId,
				recipientName: member.first_name
			});
		}

		// Audit log
		logMemberAction('status_change',
			{ id: session.user.id, email: session.user.email! },
			{ id: memberId, email: member?.email },
			{ old_status: 'pending', new_status: 'inactive', action: 'rejected', reason }
		);

		return { success: true, rejected: member?.first_name };
	}
};
