// routes/auth.js
import express from 'express';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import Login from '../models/login.js';
import Mapping from '../models/mapping.js';
import Client from '../models/client.js';
import Treelogy from '../models/treelogy.js';
import UserMaster from '../models/userMaster.js';
import { getRoleNames } from '../middleware/auth.js';

const router = express.Router();

router.post('/login', async (req, res) => {
  console.log("req arruved")
  try {
    const { identifierType = 'mobile', identifier, password, treelogy_id } = req.body;

    // For Super Admin, treelogy_id can be null
    const isSuperAdminLogin = identifierType === 'member' && identifier === 'root';
    
    if (!identifier || !password) {
      return res.status(400).json({ success: false, message: 'identifier and password are required' });
    }
    
    // Only require treelogy_id for PROJECT_USER level users, not for CLIENT_ADMIN
    // CLIENT_ADMIN should be able to login without specifying a project
    const where = {};
    if (identifierType === 'mobile') where.mobile_number = identifier;
    else where.member_id = identifier;
    
    // For Super Admin, don't filter by treelogy_id
    // For CLIENT_ADMIN, QC_USER, QC_USER_2 - also don't filter by treelogy_id - they can access all their client's projects
    // Only PROJECT_USER level users need to specify treelogy_id
    // If treelogy_id is explicitly provided, use it; otherwise don't filter
    if (!isSuperAdminLogin && treelogy_id !== null && treelogy_id !== undefined) {
      where.treelogy_id = treelogy_id;
    }

    const user = await Login.findOne({
      where,
      include: [ 
        { model: Client, foreignKey: 'client_id' },
        { model: Treelogy, foreignKey: 'treelogy_id' },
        { model: Mapping, foreignKey: 'login_id' },
        { model: UserMaster, foreignKey: 'role_id' }
      ]
    });

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

    const ok = await bcrypt.compare(password, user.password);
    if (!ok) return res.status(401).json({ success: false, message: 'Invalid credentials' });

    const payload = {
      login_id: user.login_id,
      client_id: user.client_id,
      treelogy_id: user.treelogy_id,
      role_id: user.role_id,
      role_name: user.UserMaster?.role_name,
      name: user.name
    };

    const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '12h' });

    // Build projects array based on user role
    let projects = [];
    const { role_name, client_id, login_id } = payload;

    // Get role names dynamically
    const roleNames = await getRoleNames();
    const SUPER_ADMIN = roleNames.find(name => name === 'SUPER_ADMIN');
    const CLIENT_ADMIN = roleNames.find(name => name === 'CLIENT_ADMIN');

    if (role_name === SUPER_ADMIN) {
      const all = await Treelogy.findAll({ 
        include: [{ model: Client, attributes: ['id','client_name'] }] 
      });
      projects = all;
    } else if (role_name === CLIENT_ADMIN && client_id) {
      const all = await Treelogy.findAll({
        where: { client_id },
        include: [{ model: Client, attributes: ['id','client_name'] }]
      });
      projects = all;
    } else {
      // Other roles: use Mapping first, then fallback to direct treelogy_id
      const maps = await Mapping.findAll({ where: { login_id } });
      const ids = maps.map(m => m.treelogy_id).filter(Boolean);
      
      // If no mappings found, check if user has a direct treelogy_id
      if (ids.length === 0 && user.treelogy_id) {
        ids.push(user.treelogy_id);
      }
      
      if (ids.length > 0) {
        const rows = await Treelogy.findAll({
          where: { treelogy_id: ids },
          include: [{ model: Client, attributes: ['id','client_name'] }]
        });
        projects = rows;
      }
    }

    return res.json({
      success: true,
      token,
      user: payload,
      mappings: user.Mappings?.map(m => ({
        id: m.id,
        unit_id: m.unit_id,
        role: m.role,
        view_permission: m.view_permission,
        code: m.code,
        description: m.description
      })) || [],
      projects
    });
  } catch (e) {
    console.error('Login error:', e);
    return res.status(500).json({ success: false, message: 'Login error', error: e.message });
  }
});

export default router;
