"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.createOrganization = createOrganization;
exports.getOrganization = getOrganization;
exports.addMember = addMember;
exports.removeMember = removeMember;
exports.createTeam = createTeam;
exports.addToTeam = addToTeam;
exports.getAuditLog = getAuditLog;
exports.listOrganizations = listOrganizations;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const ORG_DIR = path.join(os.homedir(), '.fivo', 'cell', 'orgs');
const AUDIT_LOG = [];
const MAX_AUDIT = 1000;
function ensureDir() { if (!fs.existsSync(ORG_DIR))
    fs.mkdirSync(ORG_DIR, { recursive: true }); }
function orgPath(id) { return path.join(ORG_DIR, `${id.replace(/[^a-zA-Z0-9_-]/g, '_')}.json`); }
function audit(actor, action, resource, detail) {
    AUDIT_LOG.push({ timestamp: Date.now(), actor, action, resource, detail });
    if (AUDIT_LOG.length > MAX_AUDIT)
        AUDIT_LOG.splice(0, AUDIT_LOG.length - MAX_AUDIT);
}
function createOrganization(name, creatorDeviceId) {
    ensureDir();
    const org = {
        id: name.toLowerCase().replace(/[^a-z0-9-]/g, '-'),
        name,
        members: [{ deviceId: creatorDeviceId, role: 'admin', joinedAt: Date.now() }],
        teams: [],
        createdAt: Date.now(),
    };
    fs.writeFileSync(orgPath(org.id), JSON.stringify(org, null, 2), 'utf-8');
    audit(creatorDeviceId, 'org.create', org.id, `Created organization ${name}`);
    return org;
}
function getOrganization(orgId) {
    try {
        const fp = orgPath(orgId);
        return fs.existsSync(fp) ? JSON.parse(fs.readFileSync(fp, 'utf-8')) : null;
    }
    catch {
        return null;
    }
}
function addMember(orgId, deviceId, role, actorDeviceId) {
    const org = getOrganization(orgId);
    if (!org)
        return null;
    const actor = org.members.find((m) => m.deviceId === actorDeviceId);
    if (!actor || actor.role !== 'admin')
        return null;
    if (org.members.some((m) => m.deviceId === deviceId))
        return org;
    org.members.push({ deviceId, role, joinedAt: Date.now() });
    fs.writeFileSync(orgPath(orgId), JSON.stringify(org, null, 2), 'utf-8');
    audit(actorDeviceId, 'member.add', orgId, `Added ${deviceId} as ${role}`);
    return org;
}
function removeMember(orgId, deviceId, actorDeviceId) {
    const org = getOrganization(orgId);
    if (!org)
        return null;
    const actor = org.members.find((m) => m.deviceId === actorDeviceId);
    if (!actor || actor.role !== 'admin')
        return null;
    if (deviceId === actorDeviceId)
        return null;
    org.members = org.members.filter((m) => m.deviceId !== deviceId);
    fs.writeFileSync(orgPath(orgId), JSON.stringify(org, null, 2), 'utf-8');
    audit(actorDeviceId, 'member.remove', orgId, `Removed ${deviceId}`);
    return org;
}
function createTeam(orgId, name, description, actorDeviceId) {
    const org = getOrganization(orgId);
    if (!org)
        return null;
    const actor = org.members.find((m) => m.deviceId === actorDeviceId);
    if (!actor || actor.role === 'viewer')
        return null;
    const team = { id: name.toLowerCase().replace(/[^a-z0-9-]/g, '-'), name, memberDeviceIds: [actorDeviceId], description };
    org.teams.push(team);
    fs.writeFileSync(orgPath(orgId), JSON.stringify(org, null, 2), 'utf-8');
    audit(actorDeviceId, 'team.create', orgId, `Created team ${name}`);
    return org;
}
function addToTeam(orgId, teamId, deviceId, actorDeviceId) {
    const org = getOrganization(orgId);
    if (!org)
        return null;
    const team = org.teams.find((t) => t.id === teamId);
    if (!team)
        return null;
    if (!org.members.some((m) => m.deviceId === actorDeviceId && m.role !== 'viewer'))
        return null;
    if (!team.memberDeviceIds.includes(deviceId))
        team.memberDeviceIds.push(deviceId);
    fs.writeFileSync(orgPath(orgId), JSON.stringify(org, null, 2), 'utf-8');
    audit(actorDeviceId, 'team.add-member', orgId, `Added ${deviceId} to team ${teamId}`);
    return org;
}
function getAuditLog(limit = 50) {
    return AUDIT_LOG.slice(-limit);
}
function listOrganizations() {
    ensureDir();
    try {
        return fs.readdirSync(ORG_DIR).filter((f) => f.endsWith('.json')).map((f) => f.replace('.json', ''));
    }
    catch {
        return [];
    }
}
//# sourceMappingURL=organization-memory.js.map