"use strict";
// Company scoping — multi-tenant isolation for goals, agents, budgets, and tasks.
//
// Each company gets a directory under `.harness/companies/<id>/` containing
// `company.json`, `goals.json`, and `budgets.json`. All mutations emit
// events through the event store so live WebSocket clients see changes.
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.listCompanies = listCompanies;
exports.getCompany = getCompany;
exports.createCompany = createCompany;
exports.updateCompany = updateCompany;
exports.deleteCompany = deleteCompany;
const crypto = __importStar(require("crypto"));
const fs = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const eventStore_1 = require("../persistence/eventStore");
// ─── Paths ──────────────────────────────────────────────────────────
function companiesDir(projectDir) {
    return path.join(projectDir, '.harness', 'companies');
}
function companyDir(projectDir, id) {
    return path.join(companiesDir(projectDir), id);
}
function companyFile(projectDir, id) {
    return path.join(companyDir(projectDir, id), 'company.json');
}
// ─── CRUD ───────────────────────────────────────────────────────────
async function listCompanies(projectDir) {
    const dir = companiesDir(projectDir);
    let entries;
    try {
        entries = await fs.readdir(dir, { withFileTypes: true });
    }
    catch {
        return [];
    }
    const companies = [];
    for (const entry of entries) {
        if (!entry.isDirectory())
            continue;
        try {
            const raw = await fs.readFile(companyFile(projectDir, entry.name), 'utf-8');
            companies.push(JSON.parse(raw));
        }
        catch {
            // Skip corrupt or missing files.
        }
    }
    return companies;
}
async function getCompany(projectDir, id) {
    try {
        const raw = await fs.readFile(companyFile(projectDir, id), 'utf-8');
        return JSON.parse(raw);
    }
    catch {
        return undefined;
    }
}
async function createCompany(projectDir, input, now = new Date()) {
    if (!input.name?.trim())
        throw new Error('Company name is required.');
    if (!input.mission?.trim())
        throw new Error('Company mission is required.');
    const id = (input.id?.trim() || crypto.randomUUID()).slice(0, 80);
    if (!/^[a-z0-9][a-z0-9-_]*$/i.test(id))
        throw new Error('Company id must be alphanumeric with - or _ only.');
    // Check for duplicate
    const existing = await getCompany(projectDir, id);
    if (existing)
        throw new Error(`Company already exists: ${id}`);
    const company = {
        id,
        name: input.name.trim(),
        mission: input.mission.trim(),
        monthlyBudgetCents: input.monthlyBudgetCents,
        settings: input.settings ?? { defaultExecutionPolicy: 'auto' },
        createdAt: now.toISOString(),
        updatedAt: now.toISOString(),
    };
    const dir = companyDir(projectDir, id);
    await fs.mkdir(dir, { recursive: true });
    await fs.writeFile(companyFile(projectDir, id), JSON.stringify(company, null, 2), 'utf-8');
    // Initialize empty goals file
    await fs.writeFile(path.join(dir, 'goals.json'), JSON.stringify({ goals: [] }, null, 2), 'utf-8');
    // Initialize empty budgets file
    await fs.writeFile(path.join(dir, 'budgets.json'), JSON.stringify({ entries: [], spendEvents: [] }, null, 2), 'utf-8');
    await (0, eventStore_1.emitEvent)(projectDir, 'service', 'company.created', { company }, 'system', id).catch(() => { });
    return company;
}
async function updateCompany(projectDir, id, input, now = new Date()) {
    const existing = await getCompany(projectDir, id);
    if (!existing)
        throw new Error(`Company not found: ${id}`);
    const updated = {
        ...existing,
        ...(input.name !== undefined ? { name: input.name.trim() } : {}),
        ...(input.mission !== undefined ? { mission: input.mission.trim() } : {}),
        ...(input.monthlyBudgetCents !== undefined ? { monthlyBudgetCents: input.monthlyBudgetCents } : {}),
        ...(input.settings !== undefined ? { settings: input.settings } : {}),
        updatedAt: now.toISOString(),
    };
    await fs.mkdir(companyDir(projectDir, id), { recursive: true });
    await fs.writeFile(companyFile(projectDir, id), JSON.stringify(updated, null, 2), 'utf-8');
    await (0, eventStore_1.emitEvent)(projectDir, 'service', 'company.updated', { company: updated, previous: existing }, 'system', id).catch(() => { });
    return updated;
}
async function deleteCompany(projectDir, id) {
    const dir = companyDir(projectDir, id);
    try {
        await fs.access(path.join(dir, 'company.json'));
    }
    catch {
        return false;
    }
    await fs.rm(dir, { recursive: true, force: true });
    await (0, eventStore_1.emitEvent)(projectDir, 'service', 'company.deleted', { companyId: id }, 'system', id).catch(() => { });
    return true;
}
//# sourceMappingURL=company.js.map