-- This schema was adopted from the gravit launcher's wiki.
-- Create the uuid-ossp extension if it doesn't exist
CREATE EXTENSION IF NOT EXISTS "uuid-ossp"; 

-- Create the hwids table if it doesn't exist
CREATE TABLE IF NOT EXISTS hwids (
	id serial8 NOT NULL PRIMARY KEY,
	publickey bytea NULL,
	hwdiskid varchar NULL,
	baseboardserialnumber varchar NULL,
	graphiccard varchar NULL,
	displayid bytea NULL,
	bitness int NULL,
	totalmemory bigint NULL,
	logicalprocessors int NULL,
	physicalprocessors int NULL,
	processormaxfreq bigint NULL,
	battery boolean NULL,
	banned boolean NULL
);

-- Create the users table if it doesn't exist
CREATE TABLE IF NOT EXISTS users (
    uuid CHAR(36) UNIQUE DEFAULT NULL,
    accessToken CHAR(32) DEFAULT NULL,
    serverID VARCHAR(41) DEFAULT NULL,
    hwidid BIGINT REFERENCES hwids(id) DEFAULT NULL,
    username VARCHAR(32) UNIQUE DEFAULT NULL,
    password CHAR(60) UNIQUE DEFAULT NULL,
    can_have_cloak BOOLEAN DEFAULT false
);

-- Create the users_uuid_trigger_func function if it doesn't exist
CREATE OR REPLACE FUNCTION public.users_uuid_trigger_func()
    RETURNS TRIGGER
AS
$function$
    BEGIN
        IF (new.uuid IS NULL) THEN
		new.uuid = (SELECT uuid_generate_v4());
	END IF;
        return new;
    END;
$function$ LANGUAGE plpgsql;

-- Create the users_uuid_trigger trigger if it doesn't exist
CREATE OR REPLACE TRIGGER users_uuid_trigger
    BEFORE INSERT ON users
    FOR EACH ROW
EXECUTE PROCEDURE public.users_uuid_trigger_func();

-- Update the users table to generate uuids for existing rows if necessary
UPDATE users SET uuid=(SELECT uuid_generate_v4()) WHERE uuid IS NULL;



-- Add the primary key constraint to the hwids table if it doesn't exist
--ALTER TABLE public.hwids ADD CONSTRAINT hwids_pk PRIMARY KEY (id);


-- Create the unique index on the publickey column of the hwids table if it doesn't exist
CREATE UNIQUE INDEX IF NOT EXISTS hwids_publickey_idx ON hwids (publickey);

-- Add the foreign key constraint to the users table if it doesn't exist
-- ALTER TABLE public.users ADD CONSTRAINT IF NOT EXISTS users_hwids_fk FOREIGN KEY (hwidid) REFERENCES public.hwids(id);


CREATE TABLE IF NOT EXISTS chat_messages (
	id SERIAL PRIMARY KEY,
	author VARCHAR(32) REFERENCES users(username),
	datetime TIMESTAMP,
	content TEXT
);