import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { NotificationDeviceProvider } from '#providers/NotificationDeviceProvider';
import { Req, Res } from '#interfaces/IApi';
import verify from '#middlewares/auth';
import { validateZod } from '#middlewares/validators';
import { NotificationDeviceRegisterSchema } from '#contracts/notification/schema';
import { sendSuccess } from '#utils/responseUtils';

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

					const devices = await deviceProvider.getAll({
						where: {
							user_id: userId,
							is_active: true,
						},
						sortField: 'last_used_at',
						sortOrder: 'DESC',
					});

					return sendSuccess(res, devices);
				} catch (error) {
					return res.error(error);
				}
			},
		},
		post: {
			middleware: [verify, validateZod(NotificationDeviceRegisterSchema)],
			handler: async (req: Req, res: Res) => {
				try {
					const userId = req.user?.id as string;
					// Q-10: validateDeviceRegister already ensures platform and device_id are present
					const { platform, device_id, device_name, push_token, one_signal_player_id, device_info } = req.body;

					// Check if device already exists
					const existingDevice = await deviceProvider.getOne({
						where: {
							user_id: userId,
							device_id,
							platform,
						},
					});

					let device;
					if (existingDevice) {
						// Update existing device
						device = await deviceProvider.put(existingDevice.id, {
							device_name: device_name || existingDevice.device_name,
							push_token: push_token || existingDevice.push_token,
							one_signal_player_id: one_signal_player_id || existingDevice.one_signal_player_id,
							device_info: device_info || existingDevice.device_info,
							is_active: true,
							last_used_at: new Date(),
							updated_at: new Date(),
						} as any);
					} else {
						// Create new device
						device = await deviceProvider.create({
							id: crypto.randomUUID(),
							user_id: userId,
							platform,
							device_id,
							device_name,
							push_token,
							one_signal_player_id,
							device_info,
							is_active: true,
							last_used_at: new Date(),
							created_at: new Date(),
							updated_at: new Date(),
						});
					}

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