import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { Req, Res } from '#interfaces/IApi';
import verify from '#middlewares/auth';
import { validateId } from '#middlewares/validators';
import { NotificationDeviceProvider } from '#providers/NotificationDeviceProvider';
import { assertDeviceOwnership } from '#services/notification/helpers/ownershipHelper';
import { sendSuccess } from '#utils/responseUtils';

export default (_express: Application) => {
	const deviceProvider = NotificationDeviceProvider.getInstance();
	return <Resource>{
		delete: {
			middleware: [verify, validateId],
			handler: async (req: Req, res: Res) => {
				try {
					const userId = req.user?.id as string;
					const deviceId = req.params.id!;

					// Q-02: assertDeviceOwnership throws 404/403 if not found or not owned
					await assertDeviceOwnership(deviceProvider, deviceId, userId);

					// Deactivate device (soft delete)
					await deviceProvider.put(deviceId, {
						is_active: false,
						updated_at: new Date(),
					} as any);

					return sendSuccess(res, null);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
