#!/bin/bash
# Start PostgreSQL via Docker for local development

CONTAINER_NAME="makima-postgres"
POSTGRES_USER="makima"
POSTGRES_PASSWORD="makima_dev"
POSTGRES_DB="makima"
POSTGRES_PORT="5432"

# Check if container already exists
if docker ps -a --format '{{.Names}}' | grep -q "^${CONTAINER_NAME}$"; then
    echo "Container ${CONTAINER_NAME} exists. Starting..."
    docker start ${CONTAINER_NAME}
else
    echo "Creating new PostgreSQL container..."
    docker run -d \
        --name ${CONTAINER_NAME} \
        -e POSTGRES_USER=${POSTGRES_USER} \
        -e POSTGRES_PASSWORD=${POSTGRES_PASSWORD} \
        -e POSTGRES_DB=${POSTGRES_DB} \
        -p ${POSTGRES_PORT}:5432 \
        -v makima_postgres_data:/var/lib/postgresql/data \
        postgres:16-alpine
fi

echo "Waiting for PostgreSQL to be ready..."
until docker exec ${CONTAINER_NAME} pg_isready -U ${POSTGRES_USER} 2>/dev/null; do
    sleep 1
done

echo "PostgreSQL is ready!"
echo "Connection URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${POSTGRES_PORT}/${POSTGRES_DB}"
