<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog
  xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
                      http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-4.27.xsd">

  <changeSet id="0005-1-outbox-events" author="ordinis">
    <comment>Outbox pattern: события публикуются в Kafka @Scheduled poller'ом.</comment>
    <createTable tableName="outbox_events">
      <column name="id" type="BIGSERIAL">
        <constraints primaryKey="true" nullable="false"/>
      </column>
      <column name="event_type" type="VARCHAR(64)">
        <constraints nullable="false"/>
      </column>
      <column name="aggregate_type" type="VARCHAR(64)">
        <constraints nullable="false"/>
      </column>
      <column name="aggregate_id" type="VARCHAR(256)">
        <constraints nullable="false"/>
      </column>
      <column name="dictionary_name" type="VARCHAR(128)"/>
      <column name="data_scope" type="VARCHAR(32)">
        <constraints nullable="false"/>
      </column>
      <column name="payload" type="JSONB">
        <constraints nullable="false"/>
      </column>
      <column name="kafka_topic" type="VARCHAR(256)">
        <constraints nullable="false"/>
      </column>
      <column name="kafka_key" type="VARCHAR(512)">
        <constraints nullable="false"/>
      </column>
      <column name="created_at" type="TIMESTAMPTZ" defaultValueComputed="NOW()">
        <constraints nullable="false"/>
      </column>
      <column name="published_at" type="TIMESTAMPTZ"/>
      <column name="trace_id" type="VARCHAR(64)"/>
      <column name="span_id" type="VARCHAR(64)"/>
      <column name="attempt_count" type="INTEGER" defaultValueNumeric="0">
        <constraints nullable="false"/>
      </column>
      <column name="last_error" type="TEXT"/>
    </createTable>

    <!-- Partial index: poller сканирует только unpublished -->
    <sql>
      CREATE INDEX idx_outbox_unpublished ON outbox_events (created_at)
      WHERE published_at IS NULL;
    </sql>
  </changeSet>

</databaseChangeLog>
