-- AtlasOS - Calypso
-- Add ZFS Datasets Table
-- Version: 5.0
-- Description: Stores ZFS dataset metadata in database for faster queries and consistency

-- ZFS datasets table
CREATE TABLE IF NOT EXISTS zfs_datasets (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(512) NOT NULL UNIQUE, -- Full dataset name (e.g., pool/dataset)
    pool_id UUID NOT NULL REFERENCES zfs_pools(id) ON DELETE CASCADE,
    pool_name VARCHAR(255) NOT NULL, -- Denormalized for faster queries
    type VARCHAR(50) NOT NULL, -- filesystem, volume, snapshot
    mount_point TEXT, -- Mount point path (null for volumes)
    used_bytes BIGINT NOT NULL DEFAULT 0,
    available_bytes BIGINT NOT NULL DEFAULT 0,
    referenced_bytes BIGINT NOT NULL DEFAULT 0,
    compression VARCHAR(50) NOT NULL DEFAULT 'lz4', -- off, lz4, zstd, gzip
    deduplication VARCHAR(50) NOT NULL DEFAULT 'off', -- off, on, verify
    quota BIGINT DEFAULT -1, -- -1 for unlimited, bytes otherwise
    reservation BIGINT NOT NULL DEFAULT 0, -- Reserved space in bytes
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
    created_by UUID REFERENCES users(id)
);

-- Create indexes for faster lookups
CREATE INDEX IF NOT EXISTS idx_zfs_datasets_pool_id ON zfs_datasets(pool_id);
CREATE INDEX IF NOT EXISTS idx_zfs_datasets_pool_name ON zfs_datasets(pool_name);
CREATE INDEX IF NOT EXISTS idx_zfs_datasets_name ON zfs_datasets(name);
CREATE INDEX IF NOT EXISTS idx_zfs_datasets_type ON zfs_datasets(type);
CREATE INDEX IF NOT EXISTS idx_zfs_datasets_created_by ON zfs_datasets(created_by);

-- Composite index for common queries (list datasets by pool)
CREATE INDEX IF NOT EXISTS idx_zfs_datasets_pool_type ON zfs_datasets(pool_id, type);

