CREATE FUNCTION handle_updated_at()
RETURNS trigger
LANGUAGE plpgsql
  SET search_path = ''
AS $$
BEGIN
  NEW.updated_at = now();
  RETURN NEW;
END;
$$;

INSERT INTO storage.buckets (id, name, public)
VALUES ('files_bucket', 'files_bucket', true);

CREATE POLICY "Whack"
    ON storage.objects
    FOR ALL
    USING (bucket_id = 'files_bucket');

CREATE TABLE study_spaces (
    id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    title text NOT NULL,
    created_at timestamp with time zone DEFAULT now(),
    updated_at timestamp with time zone DEFAULT now()
);

CREATE TABLE study_space_images (
    study_space_id uuid REFERENCES study_spaces(id) ON DELETE CASCADE,
    image_path text NOT NULL,
    created_at timestamp with time zone DEFAULT now(),
    updated_at timestamp with time zone DEFAULT now(),
    PRIMARY KEY (study_space_id, image_path)
);

-- Triggers
CREATE TRIGGER study_spaces_updated_at
AFTER UPDATE ON study_spaces
FOR EACH ROW EXECUTE FUNCTION handle_updated_at();

CREATE TRIGGER study_space_images_updated_at
AFTER UPDATE ON study_space_images
FOR EACH ROW EXECUTE FUNCTION handle_updated_at();
