/**
 * Auth Controller
 * Handles authentication requests (register, login, logout, me)
 */

import { Request, Response } from 'express';
import { prisma } from '../lib/prisma';
import { PasswordService } from '../services/password.service';
import { AuthService } from '../services/auth.service';

export class AuthController {
  /**
   * Register a new user
   * POST /api/auth/register
   */
  static async register(req: Request, res: Response): Promise<void> {
    try {
      const { username, email, password } = req.body;

      // Validate required fields
      if (!username || !password) {
        res.status(400).json({
          success: false,
          error: '用户名和密码必填',
        });
        return;
      }

      // Check password strength
      const strengthCheck = PasswordService.checkStrength(password);
      if (!strengthCheck.isStrong) {
        res.status(400).json({
          success: false,
          error: strengthCheck.reason,
        });
        return;
      }

      // Check if username already exists
      const existingUser = await prisma.user.findUnique({
        where: { username },
      });

      if (existingUser) {
        res.status(409).json({
          success: false,
          error: '用户名已存在',
        });
        return;
      }

      // Check if email already exists
      if (email) {
        const existingEmail = await prisma.user.findUnique({
          where: { email },
        });

        if (existingEmail) {
          res.status(409).json({
            success: false,
            error: '邮箱已被注册',
          });
          return;
        }
      }

      // Hash password
      const password_hash = await PasswordService.hash(password);

      // Create user
      const user = await prisma.user.create({
        data: {
          username,
          email,
          password_hash,
        },
      });

      // Generate token
      const token = AuthService.generateToken({ user_id: user.id });

      // Return user data (without password)
      const { password_hash: _, ...userWithoutPassword } = user;

      res.status(201).json({
        success: true,
        data: {
          token,
          user: userWithoutPassword,
        },
      });
    } catch (error) {
      console.error('Register error:', error);
      res.status(500).json({
        success: false,
        error: '注册失败',
      });
    }
  }

  /**
   * Login user
   * POST /api/auth/login
   */
  static async login(req: Request, res: Response): Promise<void> {
    try {
      const { username, password } = req.body;

      // Validate required fields
      if (!username || !password) {
        res.status(400).json({
          success: false,
          error: '用户名和密码必填',
        });
        return;
      }

      // Find user by username or email
      const user = await prisma.user.findFirst({
        where: {
          OR: [{ username }, { email: username }],
        },
      });

      if (!user) {
        res.status(401).json({
          success: false,
          error: '用户名或密码错误',
        });
        return;
      }

      // Verify password
      const isValid = await PasswordService.verify(password, user.password_hash);

      if (!isValid) {
        res.status(401).json({
          success: false,
          error: '用户名或密码错误',
        });
        return;
      }

      // Generate token
      const token = AuthService.generateToken({ user_id: user.id });

      // Return user data (without password)
      const { password_hash: _, ...userWithoutPassword } = user;

      res.status(200).json({
        success: true,
        data: {
          token,
          user: userWithoutPassword,
        },
      });
    } catch (error) {
      console.error('Login error:', error);
      res.status(500).json({
        success: false,
        error: '登录失败',
      });
    }
  }

  /**
   * Get current user
   * GET /api/auth/me
   */
  static async me(req: Request, res: Response): Promise<void> {
    try {
      // User is attached by authenticate middleware
      const userId = req.user!.user_id;

      const user = await prisma.user.findUnique({
        where: { id: userId },
      });

      if (!user) {
        res.status(404).json({
          success: false,
          error: '用户不存在',
        });
        return;
      }

      // Return user data (without password)
      const { password_hash: _, ...userWithoutPassword } = user;

      res.status(200).json({
        success: true,
        data: userWithoutPassword,
      });
    } catch (error) {
      console.error('Get me error:', error);
      res.status(500).json({
        success: false,
        error: '获取用户信息失败',
      });
    }
  }

  /**
   * Logout
   * POST /api/auth/logout
   * Note: With JWT, logout is client-side (remove token)
   */
  static async logout(_req: Request, res: Response): Promise<void> {
    // With JWT, logout is typically handled client-side
    // Server-side may implement token blacklist if needed
    res.status(200).json({
      success: true,
      message: '登出成功',
    });
  }
}
