"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 __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
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;
    };
})();
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var CliVnetRepository_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CliVnetRepository = void 0;
const common_1 = require("@nestjs/common");
const fs = __importStar(require("node:fs"));
const path = __importStar(require("node:path"));
const uuid_1 = require("uuid");
const profile_manager_1 = require("../profile-manager");
let CliVnetRepository = CliVnetRepository_1 = class CliVnetRepository {
    constructor() {
        this.logger = new common_1.Logger(CliVnetRepository_1.name);
        this.dataDir = profile_manager_1.ProfileManager.getProfileDir();
        this.dataFile = path.join(this.dataDir, 'vnets.json');
        this.ensureDataDir();
    }
    ensureDataDir() {
        if (!fs.existsSync(this.dataDir)) {
            fs.mkdirSync(this.dataDir, { recursive: true, mode: 0o700 });
        }
    }
    load() {
        if (!fs.existsSync(this.dataFile))
            return [];
        try {
            const data = fs.readFileSync(this.dataFile, 'utf-8');
            return JSON.parse(data);
        }
        catch (error) {
            this.logger.error(`Failed to load vnets from ${this.dataFile}:`, error);
            return [];
        }
    }
    persist(records) {
        const data = JSON.stringify(records, null, 2);
        fs.writeFileSync(this.dataFile, data, { encoding: 'utf-8', mode: 0o600 });
    }
    async findActive() {
        const records = this.load();
        return records.length > 0 ? records[0] : null;
    }
    async findByProviderResourceId(providerResourceId) {
        return (this.load().find((r) => r.providerResourceId === providerResourceId) ||
            null);
    }
    async save(record) {
        const records = this.load();
        const now = new Date();
        if (!record.id) {
            record.id = (0, uuid_1.v4)();
            record.createdAt = now;
        }
        record.updatedAt = now;
        if (!record.subnets)
            record.subnets = [];
        const idx = records.findIndex((r) => r.id === record.id);
        if (idx >= 0) {
            records[idx] = { ...records[idx], ...record };
        }
        else {
            records.push(record);
        }
        this.persist(records);
        return records.find((r) => r.id === record.id);
    }
    async addSubnet(vnetId, subnet) {
        const records = this.load();
        const vnet = records.find((r) => r.id === vnetId);
        if (!vnet)
            throw new Error(`VNet ${vnetId} not found`);
        const now = new Date();
        const newSubnet = {
            ...subnet,
            id: subnet.id || (0, uuid_1.v4)(),
            vnetId,
            attachedServerIds: subnet.attachedServerIds || [],
            createdAt: now,
            updatedAt: now,
        };
        vnet.subnets = [...(vnet.subnets || []), newSubnet];
        vnet.updatedAt = now;
        this.persist(records);
        return newSubnet;
    }
    async attachServerToSubnet(subnetId, serverId) {
        const records = this.load();
        for (const vnet of records) {
            const subnet = vnet.subnets?.find((s) => s.id === subnetId);
            if (subnet) {
                if (!subnet.attachedServerIds)
                    subnet.attachedServerIds = [];
                if (!subnet.attachedServerIds.includes(serverId)) {
                    subnet.attachedServerIds.push(serverId);
                    vnet.updatedAt = new Date();
                    this.persist(records);
                }
                return;
            }
        }
        this.logger.warn(`Subnet ${subnetId} not found — cannot attach ${serverId}`);
    }
    async attachServerToVNet(vnetProviderResourceId, serverId) {
        const records = this.load();
        const vnet = records.find((r) => r.providerResourceId === vnetProviderResourceId);
        if (!vnet) {
            this.logger.warn(`VNet ${vnetProviderResourceId} not found — cannot attach ${serverId}`);
            return;
        }
        const subnet = vnet.subnets?.[0];
        if (!subnet) {
            this.logger.warn(`VNet ${vnetProviderResourceId} has no subnets — cannot attach ${serverId}`);
            return;
        }
        if (!subnet.attachedServerIds)
            subnet.attachedServerIds = [];
        if (!subnet.attachedServerIds.includes(serverId)) {
            subnet.attachedServerIds.push(serverId);
            vnet.updatedAt = new Date();
            this.persist(records);
        }
    }
    async remove(id) {
        const records = this.load();
        const filtered = records.filter((r) => r.id !== id);
        if (filtered.length < records.length)
            this.persist(filtered);
    }
};
exports.CliVnetRepository = CliVnetRepository;
exports.CliVnetRepository = CliVnetRepository = CliVnetRepository_1 = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [])
], CliVnetRepository);
