CREATE TABLE IF NOT EXISTS comments (
    id BIGSERIAL PRIMARY KEY,
    parent_post_id BIGINT NOT NULL,
    parent_comment_id BIGINT,
    author_user_id BIGINT NOT NULL,
    content TEXT NOT NULL,
    upvotes INTEGER NOT NULL DEFAULT 0,
    downvotes INTEGER NOT NULL DEFAULT 0,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (parent_post_id) REFERENCES posts (id),
    FOREIGN KEY (parent_comment_id) REFERENCES comments (id),
    FOREIGN KEY (author_user_id) REFERENCES users (id)
);

-- Create a function to set created_at and updated_at on INSERT
CREATE OR REPLACE FUNCTION comments_set_timestamps_on_insert() RETURNS TRIGGER AS $$
BEGIN
    NEW.created_at = NOW();
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Create a trigger to call the function after INSERT
CREATE TRIGGER comments_set_timestamps_on_insert
BEFORE INSERT ON posts
FOR EACH ROW
EXECUTE FUNCTION set_timestamps_on_insert();

-- Create a function to set updated_at on UPDATE
CREATE OR REPLACE FUNCTION comments_set_updated_at() RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Create a trigger to call the function after UPDATE
CREATE TRIGGER comments_set_updated_at
BEFORE UPDATE ON posts
FOR EACH ROW
EXECUTE FUNCTION comments_set_updated_at();

CREATE INDEX comments_parent_post_id_index ON comments (parent_post_id);
CREATE INDEX comments_parent_comment_id_index ON comments (parent_comment_id);
CREATE INDEX comments_user_id_index ON comments (author_user_id);