---
- name: Create PostgreSQL init script directory
  ansible.builtin.file:
    path: /opt/church-website/postgres-init
    state: directory
    mode: "0755"

- name: Deploy database init script
  ansible.builtin.template:
    src: init-databases.sh.j2
    dest: /opt/church-website/postgres-init/init-databases.sh
    mode: "0755"

- name: Check if PostgreSQL container exists
  ansible.builtin.shell: docker ps -a --filter name=^{{ postgres_container_name }}$ --format '{{ '{{' }}.Status{{ '}}' }}'
  register: postgres_status
  changed_when: false

- name: Start PostgreSQL container
  ansible.builtin.shell: |
    docker run -d \
      --name {{ postgres_container_name }} \
      --restart unless-stopped \
      --network {{ docker_network }} \
      -v {{ postgres_volume }}:/var/lib/postgresql/data \
      -v /opt/church-website/postgres-init:/docker-entrypoint-initdb.d:ro \
      -e POSTGRES_USER=postgres \
      -e POSTGRES_PASSWORD={{ vault_postgres_root_password }} \
      -p 127.0.0.1:5432:5432 \
      {{ postgres_image }}
  when: postgres_status.stdout == ""

- name: Wait for PostgreSQL to be ready
  ansible.builtin.shell: docker exec {{ postgres_container_name }} pg_isready -U postgres
  register: pg_ready
  retries: 10
  delay: 3
  until: pg_ready.rc == 0
  changed_when: false

- name: Create databases and users
  ansible.builtin.shell: |
    docker exec {{ postgres_container_name }} psql -U postgres -c "
      DO \$\$
      BEGIN
        IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '{{ item.user }}') THEN
          CREATE ROLE {{ item.user }} WITH LOGIN PASSWORD '{{ item.password }}';
        END IF;
      END
      \$\$;
    "
    docker exec {{ postgres_container_name }} psql -U postgres -tc "SELECT 1 FROM pg_database WHERE datname = '{{ item.name }}'" | grep -q 1 || \
      docker exec {{ postgres_container_name }} psql -U postgres -c "CREATE DATABASE {{ item.name }} OWNER {{ item.user }}"
  loop: "{{ databases }}"
  loop_control:
    label: "{{ item.name }}"

- name: Enable PostGIS extension on each database
  ansible.builtin.shell: |
    docker exec {{ postgres_container_name }} psql -U postgres -d {{ item.name }} -c "CREATE EXTENSION IF NOT EXISTS postgis;"
  loop: "{{ databases }}"
  loop_control:
    label: "{{ item.name }}"
