CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

CREATE TYPE "OrderStatus" AS ENUM (
    'confirmed',
    'cancelled',
    'delivered',
    'payed',
    'require_refund',
    'refunded'
    );

CREATE TYPE "QuantityUnit" AS ENUM (
    'g',
    'dkg',
    'kg',
    'piece'
    );

CREATE TYPE "OrderItemState" AS ENUM (
    'valid',
    'out_of_stock'
    );

CREATE TABLE orders
(
    id               serial                                           NOT NULL PRIMARY KEY,
    buyer_id         integer,
    status           "OrderStatus" DEFAULT 'confirmed'::"OrderStatus" NOT NULL,
    order_ext_id     uuid          DEFAULT uuid_generate_v4()         NOT NULL,
    service_order_id text,
    checkout_notes   text,
    address_id       integer
);

CREATE TABLE order_addresses
(
    id      serial NOT NULL PRIMARY KEY,
    "name"  text   NOT NULL,
    email   text   NOT NULL,
    street  text   NOT NULL,
    city    text   NOT NULL,
    country text   NOT NULL,
    zip     text   NOT NULL,
    phone   text   NOT NULL
);

CREATE TABLE order_items
(
    id            serial                                             NOT NULL PRIMARY KEY,
    product_id    integer                                            NOT NULL,
    order_id      integer references orders (id) ON DELETE CASCADE   NOT NULL,
    quantity      integer          DEFAULT 0                         NOT NULL,
    quantity_unit "QuantityUnit"                                     NOT NULL,
    state         "OrderItemState" DEFAULT 'valid'::"OrderItemState" NOT NULL,
    CONSTRAINT positive_quantity CHECK ((quantity >= 0))
);
