import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { Req, Res } from '#interfaces/IApi';
import { AuthService } from '#services/auth';
import { createRateLimit } from '#middlewares/auth';
import { validateZod } from '#middlewares/validators';
import { MobileLoginBodySchema } from '#contracts/auth/schema';
import Logger from '#utils/logger';
import { Errors } from '#interfaces/error';
import type { MobileLoginData } from '#contracts/auth/schema';
import { sendSuccess } from '#utils/responseUtils';

/**
 * Mobile Login Controller
 * Bearer token authentication with device binding
 */
export default (_express: Application) => {
	return <Resource>{
		post: {
			middleware: [
				createRateLimit(15 * 60 * 1000, 20), // 15 minutes, max 20 attempts
				validateZod(MobileLoginBodySchema),
			] as any,
			handler: async (req: Req, res: Res) => {
				try {
					const { phone, password, device_info } = req.body;

					// Require device ID for mobile login
					const deviceId = req.headers['x-device-id'] as string;
					const deviceName = req.headers['x-device-name'] as string;

					if (!deviceId) {
						throw Errors.validation([
							{
								field: 'x-device-id',
								code: 'MISSING_HEADER',
								message: { vi: 'Thiếu x-device-id header', en: 'Missing x-device-id header' },
							},
						]);
					}

					const credentials = {
						phone,
						password,
						device_info: {
							...device_info,
							device_id_header: deviceId,
							device_name_header: deviceName,
						},
						ip_address: req.ip || '',
						user_agent: req.get('User-Agent') || '',
						platform: 'mobile' as const,
						device_id: deviceId,
						device_name: deviceName,
					};

					const loginResult = await AuthService.login(credentials);

					Logger.info('Mobile login successful', {
						requestId: (req as any).requestId,
						userId: loginResult.user.id,
						platform: 'mobile',
						deviceId,
					});

					// Return tokens in body for mobile apps
					const responseData = {
						user: {
							id: loginResult.user.id,
							email: loginResult.user.email,
							username: loginResult.user.username ?? null,
							first_name: loginResult.user.first_name ?? null,
							last_name: loginResult.user.last_name ?? null,
							status: loginResult.user.status ?? 'active',
							roles: loginResult.roles,
							permissions: loginResult.permissions,
							last_login_at: (loginResult.user as any).user_auth?.last_login_at ?? null,
						},
						access_token: loginResult.accessToken,
						refresh_token: loginResult.refreshToken,
						token_type: 'Bearer' as const,
					} satisfies MobileLoginData;
					return sendSuccess(res, responseData, 'Đăng nhập thành công', 'Login successful');
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
