-- 用户主表
CREATE TABLE IF NOT EXISTS user_main (
    id UUID PRIMARY KEY,
    deleted BOOLEAN NOT NULL DEFAULT FALSE,
    createdate TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
    modifydate TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);

-- 用户登录账号表
CREATE TABLE IF NOT EXISTS user_login_account (
    id UUID PRIMARY KEY,
    user_id UUID NOT NULL,
    account VARCHAR(100) NOT NULL,
    deleted BOOLEAN NOT NULL DEFAULT FALSE,
    createdate TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
    modifydate TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_user_login_account_user_main FOREIGN KEY (user_id) REFERENCES user_main(id)
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_user_login_account_active 
    ON user_login_account(account) 
    WHERE deleted = FALSE;

-- 用户密码表
CREATE TABLE IF NOT EXISTS user_login_password (
    id UUID PRIMARY KEY,
    user_id UUID NOT NULL,
    password VARCHAR(255) NOT NULL,
    deleted BOOLEAN NOT NULL DEFAULT FALSE,
    createdate TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
    modifydate TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
    CONSTRAINT fk_user_login_password_user_main FOREIGN KEY (user_id) REFERENCES user_main(id)
);

CREATE INDEX IF NOT EXISTS idx_user_login_password_user_id 
    ON user_login_password(user_id);

-- 插入测试用户（密码: 123456）
-- bcrypt hash: $2b$12$REwMlLDCbzR4UpL6MWnzE.AacihwpFvQhGs7vDKTwwyNMb1qBWOTm
DO $$
DECLARE
    v_user_id UUID := '018fa3e0-7e5c-7aaa-8b1d-9f6e4c3b2a10'::UUID;
BEGIN
    INSERT INTO user_main (id) VALUES (v_user_id);

    INSERT INTO user_login_account (id, user_id, account)
    VALUES ('018fa3e0-7e5c-7bbb-8b1d-9f6e4c3b2a10'::UUID, v_user_id, 'admin');

    INSERT INTO user_login_password (id, user_id, password)
    VALUES ('018fa3e0-7e5c-7ccc-8b1d-9f6e4c3b2a10'::UUID, v_user_id, '$2b$12$REwMlLDCbzR4UpL6MWnzE.AacihwpFvQhGs7vDKTwwyNMb1qBWOTm');
END $$;
