import { Request, Response } from 'express';
import { AuthRequest } from '../middleware/auth';
import * as authService from '../services/authService';

export const login = async (req: Request, res: Response) => {
    try {
        const { email, password } = req.body;

        if (!email || !password) {
            return res.status(400).json({ error: 'Email and password are required' });
        }

        const result = await authService.loginUser(email, password);
        res.json(result);
    } catch (error: any) {
        res.status(401).json({ error: error.message || 'Login failed' });
    }
};

export const register = async (req: Request, res: Response) => {
    try {
        const { email, password, name, role } = req.body;

        if (!email || !password || !name) {
            return res.status(400).json({ error: 'Email, password, and name are required' });
        }

        const user = await authService.registerUser(email, password, name, role);
        res.status(201).json(user);
    } catch (error: any) {
        res.status(400).json({ error: error.message || 'Registration failed' });
    }
};

export const getMe = async (req: AuthRequest, res: Response) => {
    try {
        if (!req.user) {
            return res.status(401).json({ error: 'Unauthorized' });
        }

        const user = await authService.getUserById(req.user.userId);
        res.json(user);
    } catch (error: any) {
        res.status(500).json({ error: error.message || 'Failed to get user' });
    }
};
