-- +goose Up
-- +goose StatementBegin
-- GROUPS
CREATE TABLE groups (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
    name TEXT NOT NULL UNIQUE,
    description TEXT
);

-- ROLES
CREATE TABLE roles (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
    name TEXT NOT NULL,
    scope TEXT NOT NULL,
    description TEXT,
    UNIQUE (name, scope)
);

-- PERMISSIONS
CREATE TABLE permissions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid (),
    name TEXT NOT NULL,
    scope TEXT NOT NULL,
    description TEXT,
    UNIQUE (name, scope)
);

-- USER-GROUPS (many-to-many)
CREATE TABLE user_groups (
    user_id UUID REFERENCES users (id) ON DELETE CASCADE,
    group_id UUID REFERENCES groups (id) ON DELETE CASCADE,
    PRIMARY KEY (user_id, group_id)
);

-- GROUP-ROLES (many-to-many)
CREATE TABLE group_roles (
    group_id UUID REFERENCES groups (id) ON DELETE CASCADE,
    role_id UUID REFERENCES roles (id) ON DELETE CASCADE,
    PRIMARY KEY (group_id, role_id)
);

-- ROLE-PERMISSIONS (many-to-many)
CREATE TABLE role_permissions (
    role_id UUID REFERENCES roles (id) ON DELETE CASCADE,
    permission_id UUID REFERENCES permissions (id) ON DELETE CASCADE,
    PRIMARY KEY (role_id, permission_id)
);

-- USER-ROLES (direct assignment, optional)
CREATE TABLE user_roles (
    user_id UUID REFERENCES users (id) ON DELETE CASCADE,
    role_id UUID REFERENCES roles (id) ON DELETE CASCADE,
    PRIMARY KEY (user_id, role_id)
);

-- USER-PERMISSIONS (direct assignment, optional)
CREATE TABLE user_permissions (
    user_id UUID REFERENCES users (id) ON DELETE CASCADE,
    permission_id UUID REFERENCES permissions (id) ON DELETE CASCADE,
    PRIMARY KEY (user_id, permission_id)
);

-- GROUP-PERMISSIONS (direct on group, optional)
CREATE TABLE group_permissions (
    group_id UUID REFERENCES groups (id) ON DELETE CASCADE,
    permission_id UUID REFERENCES permissions (id) ON DELETE CASCADE,
    PRIMARY KEY (group_id, permission_id)
);

-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
DROP TABLE IF EXISTS group_permissions;

DROP TABLE IF EXISTS user_permissions;

DROP TABLE IF EXISTS user_roles;

DROP TABLE IF EXISTS role_permissions;

DROP TABLE IF EXISTS group_roles;

DROP TABLE IF EXISTS user_groups;

DROP TABLE IF EXISTS permissions;

DROP TABLE IF EXISTS roles;

DROP TABLE IF EXISTS groups;

-- +goose StatementEnd
