DROP VIEW IF EXISTS view_all_data;
DROP VIEW IF EXISTS view_users_passwords;

CREATE TABLE passwords_new (
    passwordId integer NOT NULL PRIMARY KEY AUTOINCREMENT,
    users_userId integer NOT NULL,
    password varchar(90) NOT NULL,
    seed varchar(50),
    CONSTRAINT passwords_uk UNIQUE (users_userId),
    CONSTRAINT passwords_users FOREIGN KEY (users_userId)
        REFERENCES users (userId)
);

INSERT INTO passwords_new (passwordId, users_userId, password, seed)
SELECT passwordId, users_userId, password, seed
FROM passwords;

DROP TABLE passwords;

ALTER TABLE passwords_new RENAME TO passwords;

-- View: view_users_passwords
CREATE VIEW view_users_passwords AS
SELECT
    users.userId,
    users.userName,
    users.name,
    users.surName,
    passwords.passwordId,
    passwords.password,
    passwords.seed
FROM
    passwords
    JOIN users ON users.userId = passwords.users_userId;

-- View: view_all_data
CREATE VIEW view_all_data AS
SELECT
    users.userId,
    users.userName,
    users.name,
    users.surName,
    passwords.passwordId,
    passwords.password,
    apiTokens.tokenId,
    apiTokens.token,
    apiTokens.tokenName,
    apiTokens.validityStart,
    apiTokens.validityEnd,
    apiTokens.historyState,
    apiTokens.isSessionToken,
    users_groups.groups_groupId,
    uGroups.groupName
FROM
    users
    LEFT JOIN apiTokens ON users.userId = apiTokens.users_userId
    LEFT JOIN passwords ON users.userId = passwords.users_userId
    LEFT JOIN users_groups ON users.userId = users_groups.users_userId
    LEFT JOIN uGroups ON uGroups.groupId = users_groups.groups_groupId;