-- +goose Up
CREATE TABLE comms.contact (
	created TIMESTAMP WITHOUT TIME ZONE NOT NULL,
	id SERIAL NOT NULL,
	name TEXT NOT NULL,
	organization_id INTEGER NOT NULL REFERENCES organization(id),
	PRIMARY KEY(id)
);
CREATE TABLE comms.contact_email (
	address TEXT NOT NULL,
	confirmed BOOLEAN NOT NULL,
	contact_id INTEGER NOT NULL REFERENCES comms.contact(id),
	id SERIAL NOT NULL,
	is_subscribed BOOLEAN NOT NULL,
	PRIMARY KEY(address)
);
CREATE TABLE comms.contact_phone (
	can_sms BOOLEAN NOT NULL,
	confirmed_message_id INTEGER REFERENCES comms.text_log(id),
	contact_id INTEGER NOT NULL REFERENCES comms.contact(id),
	e164 TEXT NOT NULL,
	is_subscribed BOOLEAN NOT NULL,
	stop_message_id INTEGER REFERENCES comms.text_log(id),
	PRIMARY KEY(e164)
);

ALTER TABLE publicreport.report
	ADD COLUMN reporter_contact_id INTEGER REFERENCES comms.contact(id);

-- insert a placeholder contact for the system
INSERT INTO comms.contact (
	created,
	name,
	organization_id
) SELECT 
	CURRENT_TIMESTAMP,
	'Nidus',
	id
FROM organization WHERE is_catchall = TRUE;

-- insert contacts where we have names, dropping duplicates
INSERT INTO comms.contact (
	created,
	name,
	organization_id
) SELECT DISTINCT ON (reporter_name, organization_id)
	created,
	reporter_name,
	organization_id
FROM publicreport.report
WHERE reporter_name != ''
ORDER BY reporter_name, organization_id, created ASC;

UPDATE publicreport.report
SET reporter_contact_id = comms.contact.id
FROM comms.contact
WHERE comms.contact.name = report.reporter_name
AND reporter_name != '';

-- insert contacts where we don't have names
INSERT INTO comms.contact (
	created,
	name,
	organization_id
) SELECT
	created,
	reporter_name,
	organization_id
FROM publicreport.report
WHERE report.reporter_name = '';

UPDATE publicreport.report
SET reporter_contact_id = comms.contact.id
FROM comms.contact
WHERE comms.contact.created = report.created;

-- At this point every publicreport.report should have an associated contact ID.
-- We'll make sure of this via constraint before moving the email and phone data into
-- the contacts
ALTER TABLE publicreport.report
	ALTER COLUMN reporter_contact_id SET NOT NULL;

-- Now copy over all of the contact information we have into the new contact rows
INSERT INTO comms.contact_email (
	address,
	confirmed,
	contact_id,
	is_subscribed
) SELECT
	reporter_email,
	COALESCE(reporter_contact_consent, false),
	reporter_contact_id,
	FALSE
FROM publicreport.report WHERE report.reporter_email != ''
ON CONFLICT DO NOTHING;

INSERT INTO comms.contact_phone (
	can_sms,
	confirmed_message_id,
	contact_id,
	e164,
	is_subscribed,
	stop_message_id
) SELECT
	reporter_phone_can_sms,
	NULL,
	reporter_contact_id,
	reporter_phone,
	FALSE,
	NULL
FROM publicreport.report WHERE publicreport.report.reporter_phone != ''
ON CONFLICT DO NOTHING;

-- +goose Down
ALTER TABLE publicreport.report
	DROP COLUMN reporter_contact_id;
DROP TABLE comms.contact_phone;
DROP TABLE comms.contact_email;
DROP TABLE comms.contact;
