DROP TABLE recipe_items;
DROP TABLE recipes;
DROP TABLE menu_items;


ALTER TABLE products RENAME TO products_old;

CREATE TABLE products (
  "ProductID"      UUID         NOT NULL,
  "Code"           INTEGER,
  "Name"           VARCHAR(255) NOT NULL,
  "Units"          VARCHAR(255) NOT NULL,
  "Fraction"       NUMERIC      NOT NULL,
  "FractionUnits"  VARCHAR(255) NOT NULL,
  "ProductYield"   NUMERIC      NOT NULL,
  "ProductGroupID" UUID         NOT NULL,
  "LedgerID"       UUID         NOT NULL,
  cost_price       NUMERIC      NOT NULL,
  sale_price       NUMERIC      NOT NULL,
  "IsActive"       BOOLEAN      NOT NULL,
  "IsFixture"      BOOLEAN      NOT NULL,
  is_purchased     BOOLEAN      NOT NULL,
  is_sold          BOOLEAN      NOT NULL,
  PRIMARY KEY ("ProductID"),
  UNIQUE ("Name", "Units"),
  UNIQUE ("Code"),
  FOREIGN KEY ("ProductGroupID") REFERENCES product_groups ("ProductGroupID"),
  FOREIGN KEY ("LedgerID") REFERENCES ledgers ("LedgerID")
);

INSERT INTO products (
  "ProductID", "Code", "Name", "Units", "Fraction", "FractionUnits",
  "ProductYield", "ProductGroupID", "LedgerID", cost_price, sale_price,
  "IsActive", "IsFixture", is_purchased, is_sold)
  SELECT
    "ProductID",
    "Code",
    "Name",
    "Units",
    "Fraction",
    "FractionUnits",
    "ProductYield",
    "ProductGroupID",
    "LedgerID",
    "Price",
    0,
    "IsActive",
    "IsFixture",
    TRUE,
    FALSE
  FROM products_old;

ALTER TABLE batches DROP CONSTRAINT "entities_batches_ProductID_fkey";
ALTER TABLE batches ADD CONSTRAINT "batches_ProductID_fkey" FOREIGN KEY ("ProductID")
REFERENCES products ("ProductID");

ALTER TABLE inventories DROP CONSTRAINT "entities_inventories_ProductID_fkey";
ALTER TABLE inventories ADD CONSTRAINT "inventories_ProductID_fkey" FOREIGN KEY ("ProductID")
REFERENCES products ("ProductID");

DROP TABLE products_old;

CREATE TABLE recipes (
  recipe_id      UUID    NOT NULL,
  product_id     UUID    NOT NULL,
  quantity       NUMERIC NOT NULL,
  cost_price     NUMERIC NOT NULL,
  sale_price     NUMERIC NOT NULL,
  notes          VARCHAR(255),
  valid_from     DATE    NOT NULL,
  valid_to       DATE    NOT NULL,
  effective_from DATE    NOT NULL,
  effective_to   DATE,
  PRIMARY KEY (recipe_id),
  FOREIGN KEY (product_id) REFERENCES products ("ProductID")
);

CREATE TABLE recipe_items (
  recipe_item_id UUID    NOT NULL,
  recipe_id      UUID    NOT NULL,
  product_id     UUID    NOT NULL,
  quantity       INTEGER NOT NULL,
  price          INTEGER NOT NULL,
  PRIMARY KEY (recipe_item_id),
  UNIQUE (recipe_id, product_id),
  FOREIGN KEY (recipe_id) REFERENCES recipes (recipe_id),
  FOREIGN KEY (product_id) REFERENCES products ("ProductID")
);

