-- Deploy numerus:_merge_collection_into_payment to pg
-- requires: collection
-- requires: collection_attachment
-- requires: invoice_collection
-- requires: payment

begin;

set search_path to numerus, public;

alter table payment
  drop constraint if exists payment_amount_positive
, add constraint payment_amount_not_zero check (amount <> 0)
;

update payment
set amount = -amount
;

insert into payment (company_id, slug, description, payment_date, payment_account_id, amount, currency_code, tags, payment_status, created_at)
select company_id, slug, description, collection_date, payment_account_id, amount, currency_code, tags, payment_status, created_at
from collection
;

insert into payment_attachment (payment_id, original_filename, mime_type, content)
select payment_id, original_filename, mime_type, content
from collection_attachment
join collection using (collection_id)
join payment using (slug)
;

drop table collection_attachment;

insert into invoice_payment (invoice_id, payment_id)
select invoice_id, payment_id
from invoice_collection
join collection using (collection_id)
join payment using (slug)
;

drop table invoice_collection;

drop table collection;

commit;
