-- Tasks, snapshots, tagging, content library, datastore files, roles.

CREATE TABLE vsphere_tasks (
    id text PRIMARY KEY,
    description text NOT NULL DEFAULT '',
    status text NOT NULL CHECK (status IN ('PENDING', 'RUNNING', 'SUCCEEDED', 'FAILED')),
    service text NOT NULL DEFAULT '',
    operation text NOT NULL DEFAULT '',
    result jsonb,
    error jsonb,
    created_at timestamptz NOT NULL DEFAULT now(),
    updated_at timestamptz NOT NULL DEFAULT now(),
    completed_at timestamptz
);

CREATE INDEX vsphere_tasks_status_idx ON vsphere_tasks (status);

CREATE TABLE vsphere_snapshots (
    id text PRIMARY KEY,
    vm_moid text NOT NULL REFERENCES vsphere_objects (moid) ON DELETE CASCADE,
    name text NOT NULL,
    description text NOT NULL DEFAULT '',
    created_at timestamptz NOT NULL DEFAULT now(),
    props jsonb NOT NULL DEFAULT '{}'::jsonb
);

CREATE INDEX vsphere_snapshots_vm_idx ON vsphere_snapshots (vm_moid);

CREATE TABLE vsphere_tag_categories (
    id text PRIMARY KEY,
    name text NOT NULL UNIQUE,
    description text NOT NULL DEFAULT '',
    cardinality text NOT NULL DEFAULT 'MULTIPLE',
    associable_types text[] NOT NULL DEFAULT '{}'
);

CREATE TABLE vsphere_tags (
    id text PRIMARY KEY,
    category_id text NOT NULL REFERENCES vsphere_tag_categories (id) ON DELETE CASCADE,
    name text NOT NULL,
    description text NOT NULL DEFAULT '',
    UNIQUE (category_id, name)
);

CREATE TABLE vsphere_tag_associations (
    tag_id text NOT NULL REFERENCES vsphere_tags (id) ON DELETE CASCADE,
    object_type text NOT NULL,
    object_id text NOT NULL,
    PRIMARY KEY (tag_id, object_type, object_id)
);

CREATE TABLE vsphere_libraries (
    id text PRIMARY KEY,
    name text NOT NULL UNIQUE,
    description text NOT NULL DEFAULT '',
    type text NOT NULL DEFAULT 'LOCAL',
    props jsonb NOT NULL DEFAULT '{}'::jsonb
);

CREATE TABLE vsphere_library_items (
    id text PRIMARY KEY,
    library_id text NOT NULL REFERENCES vsphere_libraries (id) ON DELETE CASCADE,
    name text NOT NULL,
    type text NOT NULL DEFAULT 'ovf',
    description text NOT NULL DEFAULT '',
    props jsonb NOT NULL DEFAULT '{}'::jsonb,
    UNIQUE (library_id, name)
);

CREATE TABLE vsphere_datastore_files (
    id bigserial PRIMARY KEY,
    datastore_moid text NOT NULL REFERENCES vsphere_objects (moid) ON DELETE CASCADE,
    path text NOT NULL,
    size bigint NOT NULL DEFAULT 0,
    type text NOT NULL DEFAULT 'FILE',
    UNIQUE (datastore_moid, path)
);

CREATE TABLE vsphere_permissions (
    id bigserial PRIMARY KEY,
    principal text NOT NULL,
    role text NOT NULL,
    entity_moid text,
    propagate boolean NOT NULL DEFAULT true
);

CREATE INDEX vsphere_permissions_principal_idx ON vsphere_permissions (principal);
