/**
 * 管理端多租户：从当前登录 sys_user 解析 tenant_id
 */
const { sys_user } = require("../../middleware/baseModel");

/**
 * @param {import('koa').Context} ctx
 * @returns {Promise<{ tenantId: number|null, userId: number|null }>}
 */
async function getAdminTenantContext(ctx) {
  let uid_raw = null;
  try {
    uid_raw = ctx.getAdminUserId && ctx.getAdminUserId();
  } catch (e) {
    uid_raw = null;
  }
  if (uid_raw === null || uid_raw === undefined || uid_raw === "") {
    return { tenantId: null, userId: null };
  }
  const user_id = Number(uid_raw);
  if (!Number.isFinite(user_id) || user_id <= 0) {
    return { tenantId: null, userId: null };
  }
  if (!sys_user) {
    return { tenantId: null, userId: user_id };
  }
  const row = await sys_user.findByPk(user_id, {
    attributes: ["id", "tenant_id"],
    raw: true,
  });
  const tid_raw = row && row.tenant_id;
  const tenant_id = tid_raw != null && tid_raw !== "" ? Number(tid_raw) : null;
  const tenant_ok = tenant_id != null && Number.isFinite(tenant_id) && tenant_id > 0;
  return { tenantId: tenant_ok ? tenant_id : null, userId: user_id };
}

/**
 * @param {import('sequelize').Model} model
 * @param {object} where
 * @param {number} tenant_id
 */
function mergeTenantWhere(model, where, tenant_id) {
  if (tenant_id == null || tenant_id === "" || !model || !model.rawAttributes || !model.rawAttributes.tenant_id) {
    return where || {};
  }
  const w = where && typeof where === "object" ? { ...where } : {};
  w.tenant_id = tenant_id;
  return w;
}

function mergeTenantWhereById(model, id, tenant_id) {
  return mergeTenantWhere(model, { id }, tenant_id);
}

/**
 * @param {import('koa').Context} ctx
 * @returns {Promise<{ tenantId: number, userId: number }|null>}
 */
async function requireTenantContext(ctx) {
  const { tenantId, userId } = await getAdminTenantContext(ctx);
  if (!tenantId) {
    ctx.fail("当前用户未绑定租户，无法操作业务数据");
    return null;
  }
  if (!userId) {
    ctx.fail("未登录或登录已失效");
    return null;
  }
  return { tenantId, userId };
}

function stampTenantCreate(body, tenant_id, user_id, opts = {}) {
  const out = body && typeof body === "object" ? { ...body } : {};
  if (tenant_id != null) {
    out.tenant_id = tenant_id;
  }
  if (opts.setCreateUser !== false && user_id != null) {
    out.create_user_id = user_id;
  }
  return out;
}

module.exports = {
  getAdminTenantContext,
  requireTenantContext,
  stampTenantCreate,
  mergeTenantWhere,
  mergeTenantWhereById,
};
