-- CREATE EXTENSION IF NOT EXISTS "postgis";
-- CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE EXTENSION IF NOT EXISTS "fuzzystrmatch";

DROP TYPE IF EXISTS QUANTITY CASCADE;
CREATE TYPE QUANTITY AS ENUM ('lots', 'many', 'few', 'none');

DROP TYPE IF EXISTS CATEGORY CASCADE;
CREATE TYPE CATEGORY AS ENUM (
    'Baby & Kids', 
    'Baked Goods', 
    'Beverages', 
    'Cleaning', 
    'Dairy & Eggs', 
    'Frozen Food', 
    'Fruit & Vegetables', 
    'Health & Beauty', 
    'Home & Outdoor', 
    'Meat & Seafood', 
    'Pantry & Dry Goods',
    'Pet Supplies',
    'School & Office Supplies',
    'Toiletries'
);

DROP TABLE IF EXISTS product CASCADE;
CREATE TABLE product (
    id     VARCHAR(100),
    provider_type      VARCHAR(50),
    name               VARCHAR(200),
    photo              VARCHAR(250),
    PRIMARY KEY (id)
);

DROP TABLE IF EXISTS search_term CASCADE;
CREATE TABLE search_term (
    term            VARCHAR(200) PRIMARY KEY,
    last_queried    timestamp (1) with time zone
);

DROP TABLE IF EXISTS search_term_product CASCADE;
CREATE TABLE search_term_product (
    term        VARCHAR(200) REFERENCES search_term(term) ON DELETE CASCADE,
    product_id  VARCHAR(100) REFERENCES product(id) ON DELETE CASCADE
);

DROP TABLE IF EXISTS search_category CASCADE;
CREATE TABLE search_category (
    product_id      VARCHAR(100) REFERENCES product(id) ON DELETE CASCADE,
    category        CATEGORY
);

DROP TABLE IF EXISTS product_quantity CASCADE;
CREATE TABLE product_quantity (
	product_id      VARCHAR(100) REFERENCES product(id) ON DELETE CASCADE,
	date            timestamp (1) with time zone,
	quantity        QUANTITY NOT NULL,
	PRIMARY KEY (product_id, date)
);

DROP TABLE IF EXISTS faves CASCADE;
CREATE TABLE faves (
    product_id      VARCHAR(100) REFERENCES product(id) ON DELETE CASCADE,
    photo_url       VARCHAR(300),
    username        VARCHAR(200) NOT NULL,
    date            timestamp (1) with time zone NOT NULL,
    PRIMARY KEY (product_id)
);

CREATE VIEW latest_quantity AS
SELECT DISTINCT ON (product_id) product_id, quantity, date
FROM product_quantity
ORDER BY product_id, date DESC;
