CREATE DATABASE IF NOT EXISTS argent_registry;
USE argent_registry;

CREATE TABLE shards (
    shard_id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(50) NOT NULL,
    db_name VARCHAR(50) NOT NULL,
    host_address VARCHAR(255) NOT NULL,
    port INT NOT NULL DEFAULT 53096,
);

CREATE TABLE user_shard_map (
    user_id CHAR(36) PRIMARY KEY,
    username VARCHAR(50) UNIQUE NOT NULL,
    shard_id INT NOT NULL,
    is_active TINYINT(1) NOT NULL DEFAULT 1,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (shard_id) REFERENCES shards(shard_id)
);

CREATE TABLE cost_group_statuses (
    status_id TINYINT PRIMARY KEY,
    name VARCHAR(20) UNIQUE NOT NULL
);

CREATE TABLE cost_groups (
    group_id CHAR(36) PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    created_by CHAR(36),
    status_id TINYINT NOT NULL DEFAULT '1',
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (created_by) REFERENCES user_shard_map(user_id),
    FOREIGN KEY (status_id) REFERENCES cost_group_statuses(status_id)
);

CREATE TABLE group_roles (
    role_id TINYINT PRIMARY KEY,
    name VARCHAR(20) UNIQUE NOT NULL
);

CREATE TABLE group_members (
    group_id CHAR(36),
    user_id CHAR(36),
    role_id TINYINT DEFAULT '3',
    joined_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (group_id, user_id),
    FOREIGN KEY (group_id) REFERENCES cost_groups(group_id),
    FOREIGN KEY (role_id) REFERENCES group_roles(role_id),
    FOREIGN KEY (user_id) REFERENCES user_shard_map(user_id)
);

INSERT INTO cost_group_statuses (status_id, name) VALUES
(1, 'active'),
(2, 'settled'),
(3, 'archived');

INSERT INTO group_roles (role_id, name) VALUES
(1, 'owner'),
(2, 'editor'),
(3, 'participant');
