import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { Req, Res } from '#interfaces/IApi';
import { AuthService, TokenService } from '#services/auth';
import { createRateLimit } from '#middlewares/auth';
import { validateZod } from '#middlewares/validators';
import { WebLoginBodySchema } from '#contracts/auth/schema';
import Logger from '#utils/logger';
import { sendSuccess } from '#utils/responseUtils';
import Config from '#config';

/**
 * Web Login Controller
 * HttpOnly Cookie authentication for web browsers
 */
export default (_express: Application) => {
	return <Resource>{
		post: {
			middleware: [
				createRateLimit(15 * 60 * 1000, 10), // 15 minutes, max 10 attempts
				// csrfProtection({ enableDoubleSubmit: true, enableOriginValidation: false }), // Disabled for Swagger UI testing
				validateZod(WebLoginBodySchema),
			] as any,
			handler: async (req: Req, res: Res) => {
				try {
					const { email, password, device_info } = req.body;

					const credentials = {
						email,
						password,
						device_info,
						ip_address: req.ip || '',
						user_agent: req.get('User-Agent') || '',
						platform: 'web' as const,
					};

					const loginResult = await AuthService.login(credentials);

					// Set HttpOnly cookies for enhanced security
					const accessCookieOptions = TokenService.getAccessTokenCookieOptions();
					const refreshCookieOptions = TokenService.getRefreshTokenCookieOptions();

					res.cookie('access_token', loginResult.accessToken, accessCookieOptions);
					res.cookie('refresh_token', loginResult.refreshToken, refreshCookieOptions);

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

					const includeTokens =
						// eslint-disable-next-line no-restricted-syntax
						process.env.NODE_ENV === 'development' || Config.auth.includeTokensInResponse;

					// Return response WITHOUT tokens in body (secure by default)
					const responseData = {
						user: {
							id: loginResult.user.id,
							email: loginResult.user.email,
							username: loginResult.user.username,
							first_name: loginResult.user.first_name,
							last_name: loginResult.user.last_name,
							roles: loginResult.roles,
							permissions: loginResult.permissions,
							status: loginResult.user.status,
							last_login_at: loginResult.user.user_auth.last_login_at,
							resident_id: loginResult.residentId ?? null,
						},
						session: {
							id: loginResult.session.id,
							expires_at: loginResult.session.expires_at,
							refresh_expires_at: loginResult.session.refresh_expires_at,
							expires_in: loginResult.expires_in,
							refresh_expires_in: loginResult.refresh_expires_in,
							token_type: 'Bearer',
						},
						...(includeTokens
							? {
									access_token: loginResult.accessToken,
									refresh_token: loginResult.refreshToken,
								}
							: {}),
					};
					return sendSuccess(res, responseData, 'Đăng nhập thành công', 'Login successful');
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
