-- Create new order rows table



CREATE TYPE order_row_status AS ENUM (
  'no_status',
  'process',
  'error',
  'print',
  'packed',
  'cancelled',
  'sent'
);

CREATE TYPE order_row_type AS ENUM (
  'discount',
  'fee',
  'print',
  'stock',
  'sample',
  'refund'
);

-- TODO: new-order: how to deal with inquiries???
CREATE TYPE order_row_sub_type AS ENUM (
  'no_subtype',
  'wallpaper',
  'canvas',
  'poster',
  'framed_print',
  'inquiry_wallpaper',
  'inquiry_canvas',
  'inquiry_poster',
  'inquiry_framed_print',
  'retouch_fee',
  'contract_customer_discount',
  'discount_code',
  'wallpaper_kit',
  'canvas_frame',
  'sample',
  'admin_product'
);

-- Start sequence at 1 million for orders id table
ALTER SEQUENCE orders_id_seq RESTART WITH 1000000;

CREATE TABLE order_rows (
  id int GENERATED ALWAYS AS IDENTITY (START WITH 2500000) PRIMARY KEY,
  type order_row_type NOT NULL,
  sub_type order_row_sub_type NOT NULL,
  status order_row_status DEFAULT 'no_status',
  order_id int REFERENCES orders (id),
  designer_id int REFERENCES designers (designerid),
  inserted timestamp with time zone DEFAULT now(),
  updated timestamp with time zone,
  price numeric NOT NULL,
  commission_amount numeric DEFAULT 0.0,
  data JSONB
);

COMMENT ON COLUMN order_rows.price IS 'Price without VAT';

CREATE TRIGGER updated_timestamp BEFORE UPDATE ON public.order_rows FOR EACH ROW EXECUTE PROCEDURE public.updated_timestamp();

CREATE INDEX ON order_rows(order_id);
CREATE INDEX ON order_rows(designer_id);
CREATE INDEX ON order_rows(status);
CREATE INDEX ON order_rows(type);
CREATE INDEX ON order_rows(sub_type);

CREATE INDEX ON order_rows((data->>'inquiryid'));
CREATE INDEX ON order_rows((data->>'code'));
CREATE INDEX ON order_rows((data->>'artNo'));
CREATE INDEX ON order_rows((data->>'group'));

-- added column order_row_id to samples
ALTER TABLE samples ADD column IF NOT EXISTS order_row_id int REFERENCES order_rows (id);
