CREATE TABLE email_batches (
    id VARCHAR(64) PRIMARY KEY DEFAULT uuid_generate_v4(),
    subject VARCHAR(256) NOT NULL,
    body TEXT NOT NULL,
    from_email VARCHAR(64) NOT NULL default 'support@jamkazam.com',

    aasm_state VARCHAR(32) NOT NULL default 'pending',

    test_emails TEXT NOT NULL,
    batch_size INTEGER NOT NULL default 1000,

    started_at TIMESTAMP,
    completed_at TIMESTAMP,
    
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE email_batch_results (
    id VARCHAR(64) PRIMARY KEY DEFAULT uuid_generate_v4(),
    email_batch_id VARCHAR(64) REFERENCES email_batches(id) ON DELETE CASCADE,
    user_id VARCHAR(64) REFERENCES users(id) ON DELETE CASCADE,

    error_type VARCHAR(32),
    email_address VARCHAR(256),

    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

ALTER TABLE email_batch_results ADD CONSTRAINT email_batch_uniqkey UNIQUE (email_batch_id);
ALTER TABLE email_batch_results ADD CONSTRAINT email_user_uniqkey UNIQUE (user_id);

ALTER TABLE users ADD COLUMN opt_out_email_batch boolean DEFAULT false;
