-- Durable content-library transfer sessions and NFC leases (no process memory).

CREATE TABLE vsphere_transfer_sessions (
    id text NOT NULL,
    kind text NOT NULL CHECK (kind IN ('download', 'update')),
    library_item_id text NOT NULL REFERENCES vsphere_library_items (id) ON DELETE CASCADE,
    state text NOT NULL DEFAULT 'ACTIVE',
    files jsonb NOT NULL DEFAULT '{}'::jsonb,
    created_at timestamptz NOT NULL DEFAULT now(),
    updated_at timestamptz NOT NULL DEFAULT now(),
    PRIMARY KEY (id, kind)
);

CREATE INDEX vsphere_transfer_sessions_item_idx ON vsphere_transfer_sessions (library_item_id);
CREATE INDEX vsphere_transfer_sessions_kind_idx ON vsphere_transfer_sessions (kind);

CREATE TABLE vsphere_nfc_leases (
    id text PRIMARY KEY,
    vm_moid text NOT NULL,
    state text NOT NULL DEFAULT 'ready',
    payload jsonb NOT NULL DEFAULT '{}'::jsonb,
    created_at timestamptz NOT NULL DEFAULT now(),
    updated_at timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX vsphere_nfc_leases_vm_idx ON vsphere_nfc_leases (vm_moid);

-- Keep original seed document so DELETE can restore without Python templates.
ALTER TABLE vsphere_api_state
    ADD COLUMN IF NOT EXISTS seed_payload jsonb;
