-- Drop what is created below for developer convenience
ALTER TABLE paint DROP COLUMN IF EXISTS paint_primer_id;
DROP TABLE IF EXISTS paint_primer_sizes;
DROP TABLE IF EXISTS paint_primer;

-- Add new order row type and subtype for wall paint to be able to create orders for paint
ALTER TYPE order_row_type ADD VALUE 'paint';
ALTER TYPE order_row_sub_type ADD VALUE 'wall_paint';

-- Create paint primer table structure
-- Create paint_primer table
CREATE TABLE paint_primer (
    id               INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name             TEXT NOT NULL,
    created          timestamp with time zone NOT NULL DEFAULT now(),
    updated          timestamp with time zone DEFAULT NULL
);

CREATE TRIGGER updated_timestamp BEFORE UPDATE ON paint_primer FOR EACH ROW EXECUTE PROCEDURE updated_timestamp();

INSERT INTO paint_primer (name)
VALUES
  ('A-base'),
  ('C-base');

-- Create paint_primer_sizes table
CREATE TABLE paint_primer_sizes (
    id               INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    paint_primer_id  INTEGER NOT NULL REFERENCES paint_primer(id),
    liters           NUMERIC NOT NULL,
    stock            INTEGER NOT NULL DEFAULT 0,
    created          timestamp with time zone NOT NULL DEFAULT now(),
    updated          timestamp with time zone DEFAULT NULL
);

CREATE TRIGGER updated_timestamp BEFORE UPDATE ON paint_primer_sizes FOR EACH ROW EXECUTE PROCEDURE updated_timestamp();

-- Insert mock paint primer data (for now)
INSERT INTO paint_primer_sizes (paint_primer_id, liters, stock)
VALUES
  ((SELECT id FROM paint_primer WHERE name = 'A-base'), 5, 1),
  ((SELECT id FROM paint_primer WHERE name = 'A-base'), 3, 1),
  ((SELECT id FROM paint_primer WHERE name = 'A-base'), 1, 1),
  ((SELECT id FROM paint_primer WHERE name = 'C-base'), 5, 1),
  ((SELECT id FROM paint_primer WHERE name = 'C-base'), 3, 1),
  ((SELECT id FROM paint_primer WHERE name = 'C-base'), 1, 1);

-- Add paint_primer_id reference to paint
ALTER TABLE paint ADD COLUMN paint_primer_id INTEGER REFERENCES paint_primer(id);

-- Populate to allow for not null constraint
UPDATE paint SET paint_primer_id = (SELECT id FROM paint_primer WHERE name = 'A-base');

-- Add NOT NULL constraint to paint_primer_id for paint.
ALTER TABLE paint ALTER COLUMN paint_primer_id SET NOT NULL;
