/**
 * 系统租户 sys_tenant：表单下拉（平台租户可看全部启用租户，否则仅本租户）
 */
const baseModel = require("../../middleware/baseModel");
const { getAdminTenantContext } = require("../service/tenant_scope");

module.exports = {
  "GET /sys_tenant/form_options": async (ctx) => {
    const sys_tenant = baseModel.sys_tenant;
    if (!sys_tenant) {
      return ctx.fail("sys_tenant 模型未加载");
    }
    const { tenantId: user_tenant_id, userId } = await getAdminTenantContext(ctx);
    const uid = userId != null && userId !== "" ? Number(userId) : null;
    const has_user = Number.isFinite(uid) && uid > 0;
    if (!has_user) {
      return ctx.fail("未登录或登录已失效");
    }
    const tid = user_tenant_id != null && user_tenant_id !== "" ? Number(user_tenant_id) : null;
    const user_tenant_ok = Number.isFinite(tid) && tid > 0;

    let is_platform = false;
    if (user_tenant_ok) {
      const row = await sys_tenant.findByPk(tid, {
        attributes: ["id", "is_platform"],
        raw: true,
      });
      if (row && Number(row.is_platform) === 1) {
        is_platform = true;
      }
    }

    let rows;
    if (is_platform) {
      rows = await sys_tenant.findAll({
        where: { status: 1 },
        order: [["id", "ASC"]],
        limit: 500,
        raw: true,
      });
    } else if (user_tenant_ok) {
      const one = await sys_tenant.findByPk(tid, { raw: true });
      rows = one ? [one] : [];
    } else {
      rows = [];
    }

    const list = (rows || []).map((r) => {
      const id = Number(r.id);
      const name = r.name != null ? String(r.name).trim() : "";
      const plat = Number(r.is_platform) === 1;
      return {
        key: id,
        value: plat && name ? `${name}（平台）` : name || String(id),
      };
    });
    const locked = !is_platform;
    const defaultTenantId = user_tenant_ok ? tid : null;
    return ctx.success({ list, locked, defaultTenantId });
  },
};
