-- ------------------------
-- Metadata table (singleton)
-- ------------------------
DROP TABLE IF EXISTS metadata;

CREATE TABLE metadata (
    name VARCHAR(50),
    comment VARCHAR(200),
    private_key VARCHAR(500),
    public_key VARCHAR(500)
);

INSERT INTO metadata DEFAULT VALUES;

-- ------------------------
-- Entity table
-- ------------------------
DROP TABLE IF EXISTS entity CASCADE;

CREATE TABLE entity (
    id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    creation_ts TIMESTAMPTZ NOT NULL DEFAULT now(),
    creator INT REFERENCES entity(id),
    name VARCHAR(100) NOT NULL,
    type VARCHAR(10) NOT NULL DEFAULT 'person', -- 'creator', 'person', 'group', 'device'
    geo_offset BIGINT,
    public_key VARCHAR(300) NOT NULL,
    expiration DATE,
    status VARCHAR(10) NOT NULL DEFAULT 'active'
);

-- Indexes
CREATE INDEX idx_entity_name ON entity(name);
CREATE INDEX idx_entity_expiration ON entity(expiration);

ALTER TABLE entity ADD CONSTRAINT entity_name_unique UNIQUE (name);

-- ------------------------
-- Group Member table
-- ------------------------
DROP TABLE IF EXISTS group_member;

CREATE TABLE group_member (
    group_id INT NOT NULL REFERENCES entity(id) ON DELETE CASCADE,
    member_id INT NOT NULL REFERENCES entity(id) ON DELETE CASCADE,
    role VARCHAR(10),
    PRIMARY KEY (group_id, member_id)
);

CREATE INDEX idx_group_member_member_group ON group_member(member_id, group_id);

-- ------------------------
-- Property table
-- ------------------------
DROP TABLE IF EXISTS property;

CREATE TABLE property (
    id INT NOT NULL REFERENCES entity(id) ON DELETE CASCADE,
    property_name VARCHAR(100),
    PRIMARY KEY (id, property_name)
);

