const assert = require('node:assert/strict');
const sinon = require('sinon');
const errors = require('@tryghost/errors');
const {MemberCreatedEvent} = require('../../../../core/server/models/member-created-event');

describe('Unit: models/MemberCreatedEvent', function () {
    afterEach(function () {
        sinon.restore();
    });

    describe('validation', function () {
        it('throws error for invalid attribution_type', function () {
            return MemberCreatedEvent.add({attribution_type: 'invalid', source: 'member', member_id: '123'})
                .then(function () {
                    throw new Error('expected ValidationError');
                })
                .catch(function (err) {
                    assert.equal(err.length, 1);
                    assert.equal((err[0] instanceof errors.ValidationError), true);
                    assert.match(err[0].context, /members_created_events\.attribution_type/);
                });
        });

        it('throws if member_id is missing', function () {
            return MemberCreatedEvent.add({attribution_type: 'post', source: 'member'})
                .then(function () {
                    throw new Error('expected ValidationError');
                })
                .catch(function (err) {
                    assert.equal(err.length, 1);
                    assert.equal((err[0] instanceof errors.ValidationError), true);
                    assert.match(err[0].context, /members_created_events\.member_id/);
                });
        });

        it('throws if source is missing', function () {
            return MemberCreatedEvent.add({attribution_type: 'post', member_id: '123'})
                .then(function () {
                    throw new Error('expected ValidationError');
                })
                .catch(function (err) {
                    assert.equal(err.length, 1);
                    assert.equal((err[0] instanceof errors.ValidationError), true);
                    assert.match(err[0].context, /members_created_events\.source/);
                });
        });

        it('throws if source is invalid', function () {
            return MemberCreatedEvent.add({attribution_type: 'post', member_id: '123', source: 'invalid'})
                .then(function () {
                    throw new Error('expected ValidationError');
                })
                .catch(function (err) {
                    assert.equal(err.length, 1);
                    assert.equal((err[0] instanceof errors.ValidationError), true);
                    assert.match(err[0].context, /members_created_events\.source/);
                });
        });
    });
});
