CREATE TABLE marketings (
    id BIGSERIAL PRIMARY KEY,
    so_number VARCHAR(255) UNIQUE NOT NULL,
    customer_id BIGINT NOT NULL,
    so_docs VARCHAR(20),
    so_date DATE NOT NULL,
    sales_person_id BIGINT NOT NULL,
    notes TEXT,
    created_by BIGINT NOT NULL,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW(),
    deleted_at TIMESTAMPTZ
);

DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'customers') THEN
        ALTER TABLE marketings
            ADD CONSTRAINT fk_marketings_customer_id 
            FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE RESTRICT;
    END IF;

    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'users') THEN
        ALTER TABLE marketings
            ADD CONSTRAINT fk_marketings_sales_person_id 
            FOREIGN KEY (sales_person_id) REFERENCES users(id) ON DELETE RESTRICT;
    END IF;

    IF EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'users') THEN
        ALTER TABLE marketings
            ADD CONSTRAINT fk_marketings_created_by 
            FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE RESTRICT;
    END IF;
END $$;

CREATE INDEX idx_marketings_customer_id ON marketings (customer_id);

CREATE INDEX idx_marketings_sales_person_id ON marketings (sales_person_id);

CREATE INDEX idx_marketings_created_by ON marketings (created_by);

CREATE INDEX idx_marketings_so_date ON marketings (so_date);

CREATE INDEX idx_marketings_deleted_at ON marketings (deleted_at);