import Treelogy from '../models/treelogy.js';
import Mapping from '../models/mapping.js';
import Client from '../models/client.js';
import { successResponse, errorResponse } from '../utils/response.js';
import { getRoleNames } from '../middleware/auth.js';

export async function myProjects(req, res) {
  try {
    const { role_name, client_id, login_id } = req.user;

    // 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'] }] });
      return successResponse(res, 200, 'OK', all);
    }

    if (role_name === CLIENT_ADMIN && client_id) {
      const all = await Treelogy.findAll({
        where: { client_id },
        include: [{ model: Client, attributes: ['id','client_name'] }]
      });
      return successResponse(res, 200, 'OK', all);
    }

    // PROJECT_USER or others: use Mapping
    const maps = await Mapping.findAll({ where: { login_id } });
    const ids = maps.map(m => m.treelogy_id).filter(Boolean);
    if (ids.length === 0) return successResponse(res, 200, 'OK', []);
    const rows = await Treelogy.findAll({
      where: { treelogy_id: ids },
      include: [{ model: Client, attributes: ['id','client_name'] }]
    });
    return successResponse(res, 200, 'OK', rows);
  } catch (e) {
    return errorResponse(res, 500, 'Error fetching my projects', e.message);
  }
}