import { FastifyInstance } from 'fastify';
import { AuthService } from '../services/auth.service';
import { authMiddleware, adminMiddleware } from '../middleware/auth';

const authService = new AuthService();

export async function authRoutes(app: FastifyInstance): Promise<void> {
  /**
   * POST /api/auth/register - 用户注册
   */
  app.post('/api/auth/register', async (request, reply) => {
    try {
      const { email, password } = request.body as { email: string; password: string };

      if (!email || !password) {
        return reply.status(400).send({
          success: false,
          error: 'VALIDATION_ERROR',
          message: 'Email and password are required',
        });
      }

      if (password.length < 6) {
        return reply.status(400).send({
          success: false,
          error: 'VALIDATION_ERROR',
          message: 'Password must be at least 6 characters',
        });
      }

      const result = await authService.register({ email, password });
      return reply.send({ success: true, data: result });
    } catch (err: any) {
      if (err.message === 'EMAIL_EXISTS') {
        return reply.status(409).send({
          success: false,
          error: 'EMAIL_EXISTS',
          message: 'Email already registered',
        });
      }
      throw err;
    }
  });

  /**
   * POST /api/auth/login - 用户登录
   */
  app.post('/api/auth/login', async (request, reply) => {
    try {
      const { email, password } = request.body as { email: string; password: string };

      if (!email || !password) {
        return reply.status(400).send({
          success: false,
          error: 'VALIDATION_ERROR',
          message: 'Email and password are required',
        });
      }

      const result = await authService.login({ email, password });
      return reply.send({ success: true, data: result });
    } catch (err: any) {
      if (err.message === 'INVALID_CREDENTIALS') {
        return reply.status(401).send({
          success: false,
          error: 'INVALID_CREDENTIALS',
          message: 'Invalid email or password',
        });
      }
      throw err;
    }
  });

  /**
   * GET /api/auth/me - 获取当前用户信息
   */
  app.get('/api/auth/me', { preHandler: [authMiddleware] }, async (request, reply) => {
    const user = await authService.getMe(request.user!.user_id);
    if (!user) {
      return reply.status(404).send({
        success: false,
        error: 'USER_NOT_FOUND',
        message: 'User not found',
      });
    }
    return reply.send({ success: true, data: user });
  });

  /**
   * GET /api/admin/users - 管理所有用户
   */
  app.get('/api/admin/users', { preHandler: [authMiddleware, adminMiddleware] }, async (request, reply) => {
    const users = await authService.listUsers();
    return reply.send({ success: true, data: users });
  });
}
