const express = require('express');
const bcrypt = require('bcrypt');
const pool = require('../db');

const router = express.Router();

/* ============================================================
   ROLE NORMALIZER
============================================================ */
function normalizeRole(inviteRole) {
  switch (inviteRole) {
    case 'owner':
    case 'admin':
    case 'member':
      return inviteRole;

    case 'user': // legacy UI value
      return 'member';

    default:
      return 'member';
  }
}

/* ============================================================
   GET /invite/validate?token=...
============================================================ */
router.get('/validate', async (req, res) => {
  const { token } = req.query;

  if (!token) {
    return res.json({
      success: false,
      error: 'Token missing'
    });
  }

  try {
    const [[invite]] = await pool.query(
      `
      SELECT
        ui.inviteID,
        ui.email,
        ui.role,
        o.name AS organizationName
      FROM user_invites ui
      JOIN organizations o ON o.id = ui.organizationId
      WHERE ui.token = ?
        AND ui.status = 'pending'
        AND ui.expiresAt > NOW()
      `,
      [token]
    );

    if (!invite) {
      return res.json({
        success: false,
        error: 'Invite invalid or expired'
      });
    }

    res.json({
      success: true,
      email: invite.email,
      role: invite.role,
      organizationName: invite.organizationName
    });

  } catch (err) {
    console.error('Validate invite error:', err.sqlMessage || err);
    res.status(500).json({
      success: false,
      error: 'Validation failed'
    });
  }
});

/* ============================================================
   POST /invite/accept
============================================================ */
router.post('/accept', async (req, res) => {
  const { token, password, firstName, lastName } = req.body;

  if (!token || !password || !firstName || !lastName) {
    return res.status(400).json({
      success: false,
      error: 'Missing required data'
    });
  }

  const conn = await pool.getConnection();

  try {
    await conn.beginTransaction();

    const [[invite]] = await conn.query(
      `
      SELECT *
      FROM user_invites
      WHERE token = ?
        AND status = 'pending'
        AND expiresAt > NOW()
      FOR UPDATE
      `,
      [token]
    );

    if (!invite) {
      await conn.rollback();
      return res.status(400).json({
        success: false,
        error: 'Invalid or expired invite'
      });
    }

    const passwordHash = await bcrypt.hash(password, 12);
    const userRole = normalizeRole(invite.role);

    await conn.query(
      `
      INSERT INTO users
        (organizationId, email, firstName, lastName, password_hash, role)
      VALUES (?, ?, ?, ?, ?, ?)
      `,
      [
        invite.organizationId,
        invite.email,
        firstName,
        lastName,
        passwordHash,
        userRole
      ]
    );

    await conn.query(
      `
      UPDATE user_invites
      SET status = 'accepted',
          acceptedAt = NOW()
      WHERE inviteID = ?
      `,
      [invite.inviteID]
    );

    await conn.commit();

    res.json({ success: true });

  } catch (err) {
    await conn.rollback();
    console.error('Accept invite error:', err);

    if (err.code === 'ER_DUP_ENTRY') {
      return res.status(409).json({
        success: false,
        error: 'User already exists'
      });
    }

    res.status(500).json({
      success: false,
      error: 'Invite acceptance failed'
    });

  } finally {
    conn.release();
  }
});

module.exports = router;
