CREATE TABLE IF NOT EXISTS basket.basket
(
    id uuid NOT NULL DEFAULT gen_random_uuid(),
    "state" character varying NOT NULL DEFAULT 'new',
    created_at timestamp without time zone NOT NULL DEFAULT now(),
    updated_at timestamp without time zone,
    PRIMARY KEY (id)
);

ALTER TABLE IF EXISTS basket.basket OWNER to egommerce;

CREATE TABLE IF NOT EXISTS basket.basket_item
(
    id uuid NOT NULL DEFAULT gen_random_uuid(),
    basket_id uuid NOT NULL,
    product_id uuid NOT NULL,
    quantity integer NOT NULL DEFAULT 1,
    price double precision NOT NULL DEFAULT 0.00,
    created_at timestamp without time zone NOT NULL DEFAULT now(),
    updated_at timestamp without time zone,
    PRIMARY KEY (id),
    CONSTRAINT basket_item_basket_fkey FOREIGN KEY (basket_id)
        REFERENCES basket.basket (id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE NO ACTION
        NOT VALID
);

ALTER TABLE IF EXISTS basket.basket_item OWNER to egommerce;

CREATE FUNCTION basket.update_basket_timestamp()
    RETURNS trigger
    LANGUAGE 'plpgsql'
    VOLATILE
AS $BODY$
BEGIN
    UPDATE basket.basket SET updated_at = NOW() WHERE id = NEW.basket_id;
    RETURN NEW;
END;
$BODY$;

ALTER FUNCTION basket.update_basket_timestamp() OWNER TO egommerce;

CREATE TRIGGER trigger_update_basket_timestamp
    AFTER INSERT OR UPDATE OR DELETE ON basket.basket_item
    FOR EACH ROW
    EXECUTE FUNCTION basket.update_basket_timestamp();
