-- +goose Up

-- Same identity pattern as cartridge_recurring_items (059) — a QR label
-- stuck on the physical printer chassis is what makes "the same one"
-- unambiguous across repeat visits (client+model alone can't distinguish
-- a fleet of identical office printers). Scanning it back at intake
-- pre-fills the device fields and re-links the new order to this same
-- physical unit's history.
CREATE TABLE printer_recurring_items (
    id                    UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    client_id             UUID NOT NULL REFERENCES clients(id) ON DELETE RESTRICT,
    device_brand          TEXT,
    device_model          TEXT,
    serial_number         TEXT,
    -- Same alphabet/length as cartridge codes (059) — see
    -- internal/order/printerqr.go's generateCode.
    code                  TEXT NOT NULL UNIQUE,
    created_by_staff_id   UUID NOT NULL,
    created_by_staff_name TEXT NOT NULL,
    created_at            TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX printer_recurring_items_client_id_idx ON printer_recurring_items (client_id);

-- Nullable: only printers someone bothered to label carry this link — see
-- cartridge_items.recurring_item_id's doc comment (059) for the same
-- rationale.
ALTER TABLE orders ADD COLUMN printer_recurring_item_id UUID REFERENCES printer_recurring_items(id);
CREATE INDEX orders_printer_recurring_item_id_idx ON orders (printer_recurring_item_id) WHERE printer_recurring_item_id IS NOT NULL;

-- +goose Down
ALTER TABLE orders DROP COLUMN printer_recurring_item_id;
DROP TABLE printer_recurring_items;
