import { Request, Response } from 'express';
import { AuthService } from '../services/auth.service';
import { sendSuccess, sendError } from '../utils/apiResponse';
import logger from '../utils/logger';

export class AuthController {
    static async getCurrentUser(req: any, res: Response) {
        try {
            const userId = req.user.userId;
            const user = await AuthService.getUser(userId);
            if (!user) {
                return sendError(res, 'User not found', 404);
            }
            return sendSuccess(res, { user });
        } catch (error) {
            logger.error('Error in getCurrentUser', { error });
            return sendError(res, 'Server error', 500);
        }
    }

    static async login(req: any, res: Response) {
        try {
            const { email, password } = req.body;
            console.log(`[AuthController] Attempting login for: ${email}`);

            const result = await AuthService.login(email, password);
            console.log(`[AuthController] Login successful for: ${email}`);

            return sendSuccess(res, result);
        } catch (error: any) {
            console.error(`[AuthController] Login failed for: ${req.body?.email}. Error: ${error.message}`);

            if (error.message === 'Invalid credentials') {
                return sendError(res, error.message, 400);
            }
            if (error.message === 'Account is blocked') {
                return sendError(res, error.message, 403);
            }
            logger.error('Error in login', { error });
            return sendError(res, 'Server error', 500);
        }
    }

    static async register(req: any, res: Response) {
        try {
            const { email, password } = req.body;
            const result = await AuthService.register(email, password);
            return sendSuccess(res, result);
        } catch (error: any) {
            if (error.message === 'User already exists') {
                return sendError(res, error.message, 400);
            }
            logger.error('Error in register', { error });
            return sendError(res, 'Server error', 500);
        }
    }

    static async changePassword(req: any, res: Response) {
        try {
            const { userId, newPassword } = req.body;
            const tokenUserId = req.user.userId;

            if (tokenUserId !== userId) {
                return sendError(res, 'Forbidden', 403);
            }

            await AuthService.changePassword(userId, newPassword);
            return sendSuccess(res, null);
        } catch (error) {
            logger.error('Error in changePassword', { error });
            return sendError(res, 'Server error', 500);
        }
    }

    static async updateProfile(req: any, res: Response) {
        try {
            const userId = req.user.userId;
            await AuthService.updateProfile(userId, req.body);
            return sendSuccess(res, null);
        } catch (error: any) {
            logger.error('Error in updateProfile', { error });
            return sendError(res, error.message || 'Server error', 500);
        }
    }

    static async initializeAccount(req: any, res: Response) {
        try {
            const userId = req.user.userId;
            const { language, birthDate, height, weight, gender } = req.body;
            if (!language) {
                return sendError(res, 'Language is required', 400);
            }
            const user = await AuthService.initializeUser(userId, language, { birthDate, height, weight, gender });
            return sendSuccess(res, { user });
        } catch (error: any) {
            logger.error('Error in initializeAccount', { error });
            return sendError(res, error.message || 'Server error', 500);
        }
    }

    static async getAllUsers(req: any, res: Response) {
        try {
            if (req.user.role !== 'ADMIN') {
                return sendError(res, 'Admin access required', 403);
            }
            const users = await AuthService.getAllUsers();
            return sendSuccess(res, { users });
        } catch (error) {
            logger.error('Error in getAllUsers', { error });
            return sendError(res, 'Server error', 500);
        }
    }

    static async deleteUser(req: any, res: Response) {
        try {
            if (req.user.role !== 'ADMIN') {
                return sendError(res, 'Admin access required', 403);
            }
            const { id } = req.params;
            const adminId = req.user.userId;
            await AuthService.deleteUser(adminId, id);
            return sendSuccess(res, null);
        } catch (error: any) {
            if (error.message === 'Cannot delete yourself') {
                return sendError(res, error.message, 400);
            }
            logger.error('Error in deleteUser', { error });
            return sendError(res, 'Server error', 500);
        }
    }

    static async toggleBlockUser(req: any, res: Response) {
        try {
            if (req.user.role !== 'ADMIN') {
                return sendError(res, 'Admin access required', 403);
            }
            const { id } = req.params;
            const { block } = req.body;
            const adminId = req.user.userId;

            await AuthService.blockUser(adminId, id, block);
            return sendSuccess(res, null);
        } catch (error: any) {
            if (error.message === 'Cannot block yourself') {
                return sendError(res, error.message, 400);
            }
            logger.error('Error in toggleBlockUser', { error });
            return sendError(res, 'Server error', 500);
        }
    }

    static async resetUserPassword(req: any, res: Response) {
        try {
            if (req.user.role !== 'ADMIN') {
                return sendError(res, 'Admin access required', 403);
            }
            const { id } = req.params;
            const { newPassword } = req.body;

            await AuthService.resetUserPassword(id, newPassword);
            return sendSuccess(res, null);
        } catch (error: any) {
            if (error.message === 'Password too short') {
                return sendError(res, error.message, 400);
            }
            logger.error('Error in resetUserPassword', { error });
            return sendError(res, 'Server error', 500);
        }
    }
}
