import { Router, Request, Response } from 'express';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { prisma } from '../index';
import { asyncHandler } from '../middleware/errorHandler';
import { authenticateToken, AuthenticatedRequest } from '../middleware/auth';
import Joi from 'joi';

const router = Router();

// Validation schemas
const loginSchema = Joi.object({
  username: Joi.string().required(),
  password: Joi.string().required(),
});

// Login endpoint
router.post('/login', asyncHandler(async (req: Request, res: Response) => {
  const { error, value } = loginSchema.validate(req.body);
  
  if (error) {
    return res.status(400).json({
      success: false,
      message: error.details[0].message,
    });
  }

  const { username, password } = value;

  // Find admin user
  const admin = await prisma.adminUser.findUnique({
    where: { username },
  });

  if (!admin) {
    return res.status(401).json({
      success: false,
      message: 'Invalid credentials',
    });
  }

  // Verify password
  const isValidPassword = await bcrypt.compare(password, admin.passwordHash);
  
  if (!isValidPassword) {
    return res.status(401).json({
      success: false,
      message: 'Invalid credentials',
    });
  }

  // Update last login
  await prisma.adminUser.update({
    where: { id: admin.id },
    data: { lastLogin: new Date() },
  });

  // Generate JWT token
  const jwtSecret = process.env['JWT_SECRET'];
  const jwtExpiresIn = process.env['JWT_EXPIRES_IN'] || '24h';
  
  if (!jwtSecret) {
    return res.status(500).json({
      success: false,
      message: 'Server configuration error',
    });
  }

  const token = jwt.sign(
    { 
      userId: admin.id, 
      username: admin.username 
    },
    jwtSecret,
    { 
      expiresIn: jwtExpiresIn 
    } as jwt.SignOptions
  );

  res.json({
    success: true,
    message: 'Login successful',
    token,
    user: {
      id: admin.id,
      username: admin.username,
    },
  });
}));

// Verify token endpoint
router.get('/verify', authenticateToken, asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
  res.json({
    success: true,
    message: 'Token is valid',
    user: req.user,
  });
}));

// Logout endpoint (client-side token removal, but we can log it)
router.post('/logout', authenticateToken, asyncHandler(async (req: AuthenticatedRequest, res: Response) => {
  res.json({
    success: true,
    message: 'Logged out successfully',
  });
}));

export default router;
