-- nodes
DROP TABLE IF EXISTS nodes;
CREATE TABLE nodes (
    id         SERIAL PRIMARY KEY,
    name       VARCHAR(255) NOT NULL UNIQUE,
    provider   VARCHAR(255) NOT NULL,
    location   VARCHAR(255) NOT NULL,
    ip_address VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP
);
CREATE INDEX devices_provider_index ON nodes (provider);
CREATE INDEX devices_location_index ON nodes (location);

-- users
DROP TABLE IF EXISTS users;
CREATE TABLE users (
    id         SERIAL PRIMARY KEY,
    password   VARCHAR(255) NOT NULL,
    username   VARCHAR(255) NOT NULL UNIQUE,
    email      VARCHAR(255) NOT NULL UNIQUE,
    phone      VARCHAR(255) NOT NULL UNIQUE,
    name       VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP
);

-- user_ips
DROP TABLE IF EXISTS user_ips;
CREATE TABLE user_ips (
    id         SERIAL PRIMARY KEY,
    user_id    int          NOT NULL REFERENCES users (id)
        ON UPDATE CASCADE
        ON DELETE CASCADE,
    ip_address VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP
);
CREATE INDEX user_ips_user_id_index ON user_ips (user_id);
CREATE INDEX user_ips_ip_address_index ON user_ips (ip_address);

-- channel
DROP TABLE IF EXISTS channels;
CREATE TABLE channels (
    id               SERIAL PRIMARY KEY,
    user_id          int       NOT NULL REFERENCES users (id)
        ON UPDATE CASCADE
        ON DELETE CASCADE,
    node_id          int       NOT NULL REFERENCES nodes (id) --
        ON UPDATE CASCADE                                     --
        ON DELETE SET NULL,                                   -- 节点删除后，用户侧需要保留提取记录
    forward_snapshot VARCHAR(255),
    protocol         VARCHAR(255),
    auth_ip          bool,
    auth_pass        bool,
    username         VARCHAR(255),
    password         VARCHAR(255),
    expiration       TIMESTAMP NOT NULL,
    created_at       TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at       TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    deleted_at       TIMESTAMP
);
CREATE INDEX channel_user_id_index ON channels (user_id);
CREATE INDEX channel_node_id_index ON channels (node_id);

-- ====================
-- 填充数据
-- ====================


