import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import db from '../config/database.js';

export const adminLogin = async (req, res) => {
  try {
    const { username, password } = req.body;

    const [admins] = await db.query(
      'SELECT * FROM admin_users WHERE username = ?',
      [username]
    );

    if (admins.length === 0) {
      return res.status(401).json({ success: false, message: 'Invalid credentials' });
    }

    const admin = admins[0];
    const isValidPassword = await bcrypt.compare(password, admin.password_hash);

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

    const token = jwt.sign(
      { id: admin.id, username: admin.username, role: 'admin' },
      process.env.JWT_SECRET,
      { expiresIn: '24h' }
    );

    res.json({
      success: true,
      token,
      user: {
        id: admin.id,
        username: admin.username,
        email: admin.email,
        role: 'admin'
      }
    });
  } catch (error) {
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

export const memberLogin = async (req, res) => {
  try {
    const { email, password } = req.body;

    const [members] = await db.query(
      'SELECT * FROM members WHERE email = ?',
      [email]
    );

    if (members.length === 0) {
      return res.status(401).json({ success: false, message: 'Invalid credentials' });
    }

    const member = members[0];

    // if (member.status !== 'Active') {
    //   return res.status(403).json({ success: false, message: 'Account is not active. Please wait for admin approval.' });
    // }

    const isValidPassword = await bcrypt.compare(password, member.password_hash);

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

    const token = jwt.sign(
      { id: member.id, member_id: member.member_id, role: 'member' },
      process.env.JWT_SECRET,
      { expiresIn: '24h' }
    );

    res.json({
      success: true,
      token,
      user: {
        id: member.id,
        member_id: member.member_id,
        full_name: member.full_name,
        email: member.email,
        role: 'member'
      }
    });
  } catch (error) {
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

export const customerLogin = async (req, res) => {
  try {
    const { email, password } = req.body;

    const [customers] = await db.query(
      'SELECT * FROM customers WHERE email = ?',
      [email]
    );

    if (customers.length === 0) {
      return res.status(401).json({ success: false, message: 'Invalid credentials' });
    }

    const customer = customers[0];
    const isValidPassword = await bcrypt.compare(password, customer.password_hash);

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

    const token = jwt.sign(
      { id: customer.id, customer_id: customer.customer_id, role: 'customer' },
      process.env.JWT_SECRET,
      { expiresIn: '24h' }
    );

    res.json({
      success: true,
      token,
      user: {
        id: customer.id,
        customer_id: customer.customer_id,
        full_name: customer.full_name,
        email: customer.email,
        role: 'customer'
      }
    });
  } catch (error) {
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};




// ── Forgot Password — OTP bhejo ──────────────────────────────
export const forgotPassword = async (req, res) => {
  try {
    const { email, role } = req.body;
    console.log('Forgot password request:', { email, role });

    if (!email || !role) {
      return res.status(400).json({ success: false, message: 'Email and role required' });
    }

    const tableMap = { admin: 'admin_users', member: 'members', customer: 'customers' };
    const table = tableMap[role];
    if (!table) return res.status(400).json({ success: false, message: 'Invalid role' });

    const [rows] = await db.query(`SELECT * FROM ${table} WHERE email = ?`, [email]);

    if (rows.length === 0) {
      return res.json({ success: true, message: 'If this account exists, an OTP has been sent.' });
    }

    const record = rows[0];
    const otp = generateOtp();
    const expiresAt = new Date(Date.now() + 10 * 60 * 1000);

    // ── DB insert ──
    console.log('Inserting OTP into DB...');
    await db.query(
      `INSERT INTO password_reset_otps (identifier, role, otp, expires_at, used)
       VALUES (?, ?, ?, ?, 0)
       ON DUPLICATE KEY UPDATE
         otp = VALUES(otp),
         expires_at = VALUES(expires_at),
         used = 0,
         reset_token = NULL,
         reset_token_expires = NULL`,
      [email, role, otp, expiresAt]
    );
    console.log('OTP saved to DB:', otp);

    // ── Email bhejo ──
    console.log('Sending OTP email to:', email);
    await sendOtpEmail(email, otp, record.full_name || record.username || '');
    console.log('OTP email sent successfully');

    res.json({ success: true, message: 'If this account exists, an OTP has been sent.' });

  } catch (error) {
    // ✅ Exact error print karo
    console.error('forgotPassword ERROR:', error.message);
    console.error('Stack:', error.stack);
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

// ── Verify OTP ───────────────────────────────────────────────
export const verifyOtp = async (req, res) => {
  try {
    const { email, otp, role } = req.body;

    if (!email || !otp || !role) {
      return res.status(400).json({ success: false, message: 'Email, OTP and role required' });
    }

    const [rows] = await db.query(
      `SELECT * FROM password_reset_otps
       WHERE identifier = ? AND role = ? AND otp = ? AND used = 0 AND expires_at > NOW()`,
      [email, role, otp]
    );

    if (rows.length === 0) {
      return res.status(400).json({ success: false, message: 'Invalid or expired OTP.' });
    }

    const resetToken = crypto.randomBytes(32).toString('hex');
    const tokenExpiry = new Date(Date.now() + 15 * 60 * 1000); // 15 min

    await db.query(
      `UPDATE password_reset_otps
       SET used = 1, reset_token = ?, reset_token_expires = ?
       WHERE identifier = ? AND role = ?`,
      [resetToken, tokenExpiry, email, role]
    );

    res.json({ success: true, message: 'OTP verified.', resetToken });
  } catch (error) {
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

// ── Reset Password ───────────────────────────────────────────
export const resetPassword = async (req, res) => {
  try {
    const { resetToken, newPassword } = req.body;

    if (!resetToken || !newPassword) {
      return res.status(400).json({ success: false, message: 'Token and new password required' });
    }

    if (newPassword.length < 6) {
      return res.status(400).json({ success: false, message: 'Password must be at least 6 characters' });
    }

    const [rows] = await db.query(
      `SELECT * FROM password_reset_otps WHERE reset_token = ? AND reset_token_expires > NOW()`,
      [resetToken]
    );

    if (rows.length === 0) {
      return res.status(400).json({ success: false, message: 'Invalid or expired reset token.' });
    }

    const { identifier: email, role } = rows[0];
    const passwordHash = await bcrypt.hash(newPassword, 10);

    const tableMap = { admin: 'admin_users', member: 'members', customer: 'customers' };
    const table = tableMap[role];

    await db.query(
      `UPDATE ${table} SET password_hash = ? WHERE email = ?`,
      [passwordHash, email]
    );

    await db.query('DELETE FROM password_reset_otps WHERE reset_token = ?', [resetToken]);

    res.json({ success: true, message: 'Password reset successful.' });
  } catch (error) {
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

// ── Change Password ──────────────────────────────────────────
export const changePassword = async (req, res) => {
  try {
    const { currentPassword, newPassword } = req.body;
    const { id, role } = req.user; // JWT se

    if (!currentPassword || !newPassword)
      return res.status(400).json({ success: false, message: 'Both fields required' });

    if (newPassword.length < 6)
      return res.status(400).json({ success: false, message: 'Password must be at least 6 characters' });

    // Role ke hisaab se table choose karo
    const tableMap = {
      admin:    'admin_users',
      member:   'members',
      customer: 'customers',
    };
    const table = tableMap[role];
    if (!table)
      return res.status(400).json({ success: false, message: 'Invalid role' });

    const [rows] = await db.query(`SELECT * FROM ${table} WHERE id = ?`, [id]);
    if (!rows.length)
      return res.status(404).json({ success: false, message: 'User not found' });

    const user = rows[0];

    // Current password verify karo
    const isValid = await bcrypt.compare(currentPassword, user.password_hash);
    if (!isValid)
      return res.status(401).json({ success: false, message: 'Current password is incorrect' });

    // Same password check
    const isSame = await bcrypt.compare(newPassword, user.password_hash);
    if (isSame)
      return res.status(400).json({ success: false, message: 'New password must be different from current password' });

    const newHash = await bcrypt.hash(newPassword, 10);
    await db.query(
      `UPDATE ${table} SET password_hash = ?, updated_at = NOW() WHERE id = ?`,
      [newHash, id]
    );

    res.json({ success: true, message: 'Password changed successfully' });
  } catch (error) {
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};