<?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">

  <!--
    Hibernate Envers (transaction-time audit) требует:
      - revinfo_seq      — sequence для rev id
      - revinfo          — таблица ревизий (id, timestamp)
      - dictionary_records_aud — таблица истории для @Audited entity

    Изначальный план (см. nsi-hot/audit-log) — общая audit_log table в 0004,
    но Hibernate сам генерирует *_aud для каждого @Audited. Создаём вручную,
    потому что hibernate.hbm2ddl.auto = none в production.
  -->

  <changeSet id="0010-1-envers-revinfo-seq" author="ordinis">
    <preConditions onFail="MARK_RAN">
      <not>
        <sequenceExists sequenceName="revinfo_seq"/>
      </not>
    </preConditions>
    <createSequence sequenceName="revinfo_seq" startValue="1" incrementBy="50"/>
  </changeSet>

  <changeSet id="0010-2-envers-revinfo-table" author="ordinis">
    <preConditions onFail="MARK_RAN">
      <not>
        <tableExists tableName="revinfo"/>
      </not>
    </preConditions>
    <createTable tableName="revinfo">
      <column name="rev" type="INTEGER">
        <constraints primaryKey="true" nullable="false"/>
      </column>
      <column name="revtstmp" type="BIGINT"/>
    </createTable>
  </changeSet>

  <changeSet id="0010-3-records-aud-table" author="ordinis">
    <preConditions onFail="MARK_RAN">
      <not>
        <tableExists tableName="dictionary_records_aud"/>
      </not>
    </preConditions>
    <comment>Зеркало dictionary_records + (rev, revtype) для Envers audit.</comment>
    <sql>
      CREATE TABLE dictionary_records_aud (
        id              UUID         NOT NULL,
        rev             INTEGER      NOT NULL REFERENCES revinfo(rev),
        revtype         SMALLINT,
        dictionary_id   UUID,
        business_key    VARCHAR(256),
        data            JSONB,
        geometry        GEOMETRY(Geometry, 4326),
        data_scope      VARCHAR(32),
        valid_from      TIMESTAMPTZ,
        valid_to        TIMESTAMPTZ,
        created_at      TIMESTAMPTZ,
        updated_at      TIMESTAMPTZ,
        created_by      VARCHAR(128),
        updated_by      VARCHAR(128),
        version         BIGINT,
        PRIMARY KEY (id, rev)
      );
      CREATE INDEX idx_dict_records_aud_rev ON dictionary_records_aud(rev);
      CREATE INDEX idx_dict_records_aud_id ON dictionary_records_aud(id);
    </sql>
  </changeSet>

</databaseChangeLog>
