-- Follow-up to 0002_invoices_type_and_status.sql: makes room for QPI
-- invoices to actually be insertable. QPI invoices are keyed by quarter
-- (q_key), not month/cut_number, so those columns must become optional
-- and a shape-validity check keeps the two invoice types from mixing
-- fields incorrectly.

-- 1 & 2. month/cut_number no longer required; q_key added for QPI.
alter table invoices
  alter column month drop not null,
  alter column cut_number drop not null,
  add column q_key text;

-- 3. Enforce the two valid shapes:
--   type = 'regular' -> month + cut_number required, q_key must be empty
--   type = 'qpi'     -> q_key required, month + cut_number must be empty
alter table invoices
  add constraint invoices_type_shape_check
  check (
    (type = 'regular' and month is not null and cut_number is not null and q_key is null)
    or
    (type = 'qpi' and q_key is not null and month is null and cut_number is null)
  );
