import type { NextApiRequest, NextApiResponse } from 'next';
import mysql from 'mysql2/promise';
import bcryptjs from 'bcryptjs';
import jwt from 'jsonwebtoken';

const pool = mysql.createPool({
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'perfume_shop',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
});

type ResponseData = {
  success?: boolean;
  message?: string;
  token?: string;
  user?: any;
  error?: string;
};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const { email, password } = req.body;

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

  try {
    const connection = await pool.getConnection();

    try {
      // Find user by email (check verification columns if they exist)
      let query = 'SELECT id, first_name, last_name, email, password_hash, is_active';
      try {
        // Try to select is_verified if column exists
        await connection.query('SELECT is_verified FROM users LIMIT 0');
        query += ', is_verified';
      } catch (e) {
        // Column doesn't exist, continue without it
      }
      query += ' FROM users WHERE email = ?';

      const [users]: any = await connection.query(query, [email]);

      if (users.length === 0) {
        return res.status(401).json({ error: 'Invalid email or password' });
      }

      const user = users[0];

      // Check if account is active
      if (!user.is_active) {
        return res.status(403).json({ error: 'Account is inactive' });
      }

      // Check if email is verified (if column exists)
      if (user.is_verified === undefined) {
        // Column doesn't exist, allow login (backward compatibility)
      } else if (!user.is_verified) {
        return res.status(403).json({ error: 'Prosím ověřte svůj email před přihlášením' });
      }

      // Verify password
      const isPasswordValid = await bcryptjs.compare(password, user.password_hash);

      if (!isPasswordValid) {
        return res.status(401).json({ error: 'Invalid email or password' });
      }

      // Update last login
      await connection.query(
        'UPDATE users SET last_login = NOW() WHERE id = ?',
        [user.id]
      );

      // Create JWT token
      const jwtSecret = process.env.JWT_SECRET;
      if (!jwtSecret) {
        throw new Error('JWT_SECRET is not configured');
      }

      const token = jwt.sign(
        { id: user.id, email: user.email },
        jwtSecret,
        { expiresIn: '7d' }
      );

      // Set HTTP-only cookie with Secure flag in production
      const isProduction = process.env.NODE_ENV === 'production';
      const cookieOptions = `auth_token=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=604800${isProduction ? '; Secure' : ''}`;
      res.setHeader('Set-Cookie', cookieOptions);

      return res.status(200).json({
        success: true,
        message: 'Login successful',
        token,
        user: {
          id: user.id,
          firstName: user.first_name,
          lastName: user.last_name,
          email: user.email,
        },
      });
    } finally {
      connection.release();
    }
  } catch (error) {
    return res.status(500).json({ error: 'Login failed. Please try again.' });
  }
}
