-- DB-CONTRACT-002: Complete the canonical building_blocks inbox contract.
-- Existing building_blocks.inbox_message rows remain append-only.

alter table building_blocks.inbox_message
    add column if not exists status text not null default 'Pending',
    add column if not exists error_message text,
    add column if not exists attempted_at timestamptz;

alter table building_blocks.inbox_message
    alter column received_at set default current_timestamp;

alter table building_blocks.inbox_message
    drop constraint if exists inbox_message_status_check;

alter table building_blocks.inbox_message
    add constraint inbox_message_status_check
    check (status in ('Pending', 'Processed', 'Failed'));

create or replace function building_blocks.inbox_processed_check()
returns trigger as $$
begin
    if new.status = 'Processed' and new.processed_at is null then
        raise exception 'processed_at must be set when status = Processed';
    end if;
    return new;
end;
$$ language plpgsql;

drop trigger if exists inbox_processed_check_trigger on building_blocks.inbox_message;
create trigger inbox_processed_check_trigger
before insert or update on building_blocks.inbox_message
for each row execute function building_blocks.inbox_processed_check();
