CREATE TABLE IF NOT EXISTS plans(
	plan_id serial PRIMARY KEY,
	plan_date DATE NOT NULL,
	created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL,
	updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL
);

CREATE TABLE IF NOT EXISTS actions(
	action_id serial PRIMARY KEY,
	action_description VARCHAR (500) NOT NULL,
	estimated_chunks SMALLINT,
	completed_chunks SMALLINT,
	completed_on TIMESTAMP WITH TIME ZONE,
	created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL,
	updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP NOT NULL,
	plan_id int REFERENCES plans(plan_id)
);


CREATE OR REPLACE FUNCTION trigger_set_timestamp()
RETURNS TRIGGER AS $set_updated$
BEGIN
	NEW.updated_at = NOW();
	RETURN NEW;
END;
$set_updated$ LANGUAGE plpgsql;

CREATE TRIGGER set_updated
BEFORE UPDATE ON actions
FOR EACH ROW
EXECUTE PROCEDURE trigger_set_timestamp();

CREATE TRIGGER set_updated
BEFORE UPDATE ON plans
FOR EACH ROW
EXECUTE PROCEDURE trigger_set_timestamp();
