CREATE EXTENSION IF NOT EXISTS pg_trgm;

CREATE EXTENSION IF NOT EXISTS pg_uuidv7;

CREATE TABLE
    users (
        user_id SERIAL PRIMARY KEY,
        username VARCHAR(50) NOT NULL UNIQUE,
        email VARCHAR(100) NOT NULL UNIQUE,
        hashed_password BYTEA NOT NULL
    );

CREATE TABLE
    folders (
        folder_id UUID PRIMARY KEY DEFAULT uuid_generate_v7 (),
        parent_folder_id UUID REFERENCES folders (folder_id) ON DELETE CASCADE DEFAULT null,
        owner_id INT REFERENCES users (user_id) ON DELETE CASCADE NOT NULL,
        folder_name VARCHAR(255) NOT NULL,
        created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP NOT NULL
    );

CREATE TABLE
    files (
        file_id UUID PRIMARY KEY DEFAULT uuid_generate_v7 (),
        folder_id UUID REFERENCES folders (folder_id) ON DELETE CASCADE NOT NULL,
        file_name VARCHAR(255) NOT NULL,
        file_size BIGINT NOT NULL,
        sha512 BYTEA NOT NULL,
        created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP NOT NULL,
        updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP NOT NULL
    );

CREATE TYPE permission AS ENUM ('read', 'write', 'manage');

CREATE TABLE
    permissions (
        permission_id SERIAL PRIMARY KEY,
        user_id INT REFERENCES users (user_id) ON DELETE CASCADE NOT NULL,
        folder_id UUID REFERENCES folders (folder_id) ON DELETE CASCADE,
        permission_type permission NOT NULL,
        UNIQUE (user_id, folder_id)
    );