/**
 * Shared ownership assertion helpers for notification controllers.
 * Throws a GenericError if the record is not found or doesn't belong to the requesting user.
 */
import { NotificationMessage } from '#models/NotificationMessage';
import { NotificationDevice } from '#models/NotificationDevice';
import { Errors } from '#interfaces/error';
import { NotificationMessageProvider } from '#providers/NotificationMessageProvider';
import { NotificationReceiptProvider } from '#providers/NotificationReceiptProvider';
import { NotificationDeviceProvider } from '#providers/NotificationDeviceProvider';

export async function assertNotificationOwnership(
	provider: NotificationMessageProvider,
	receiptProvider: NotificationReceiptProvider,
	notificationId: string,
	userId: string,
): Promise<NotificationMessage> {
	const notification = await provider.getById({ id: notificationId });

	if (!notification) {
		throw Errors.notFound('Thông báo');
	}

	// Check ownership via NotificationReceipt since NotificationMessage doesn't have user_id
	const receipt = await receiptProvider.getOne({
		where: {
			message_id: notificationId,
			user_id: userId,
		},
	});

	if (!receipt) {
		throw Errors.forbidden();
	}

	return notification;
}

export async function assertDeviceOwnership(
	provider: NotificationDeviceProvider,
	deviceId: string,
	userId: string,
): Promise<NotificationDevice> {
	const device = await provider.getById({ id: deviceId });

	if (!device) {
		throw Errors.notFound('Thiết bị');
	}

	if (device.user_id !== userId) {
		throw Errors.forbidden();
	}

	return device;
}
