# Build stage
# -----------------------------------------------------------
FROM rust:alpine AS builder

# Install build dependencies for backend
WORKDIR /app
RUN apk add --no-cache musl-dev pkgconfig openssl-dev openssl-libs-static

# Install sqlx-cli for migrations
RUN cargo install sqlx-cli --no-default-features --features sqlite

# Copy workspace files to maintain workspace structure
COPY ./Cargo.toml ./
COPY ./calendar-models ./calendar-models

# Create empty frontend directory to satisfy workspace
RUN mkdir -p frontend/src && \
    printf '[package]\nname = "runway"\nversion = "0.1.0"\nedition = "2021"\n\n[dependencies]\n' > frontend/Cargo.toml && \
    echo 'fn main() {}' > frontend/src/main.rs

# Copy backend files
COPY backend/Cargo.toml ./backend/

# Create dummy backend source to build dependencies first
RUN mkdir -p backend/src && \
    echo "fn main() {}" > backend/src/main.rs

# Build dependencies (this layer will be cached unless dependencies change)
RUN cargo build --release

# Copy actual backend source and build
COPY backend/src ./backend/src
COPY backend/migrations ./backend/migrations
RUN cargo build --release --bin backend

# Runtime stage
# -----------------------------------------------------------
FROM alpine:latest

# Install runtime dependencies
RUN apk add --no-cache ca-certificates tzdata sqlite

# Copy backend binary and sqlx-cli
COPY --from=builder /app/target/release/backend /usr/local/bin/backend
COPY --from=builder /usr/local/cargo/bin/sqlx /usr/local/bin/sqlx

# Copy migrations for database setup
COPY backend/migrations /migrations

# Create startup script to run migrations and start backend
RUN mkdir -p /db
RUN echo '#!/bin/sh' > /usr/local/bin/start.sh && \
    echo 'echo "Ensuring database directory exists..."' >> /usr/local/bin/start.sh && \
    echo 'mkdir -p /db && chmod 755 /db' >> /usr/local/bin/start.sh && \
    echo 'touch /db/calendar.db' >> /usr/local/bin/start.sh && \
    echo 'echo "Running database migrations..."' >> /usr/local/bin/start.sh && \
    echo 'sqlx migrate run --database-url "sqlite:///db/calendar.db" --source /migrations || echo "Migration failed but continuing..."' >> /usr/local/bin/start.sh && \
    echo 'echo "Starting backend server..."' >> /usr/local/bin/start.sh && \
    echo 'export DATABASE_URL="sqlite:///db/calendar.db"' >> /usr/local/bin/start.sh && \
    echo '/usr/local/bin/backend' >> /usr/local/bin/start.sh && \
    chmod +x /usr/local/bin/start.sh

# Start with script that runs migrations then starts backend
CMD ["/usr/local/bin/start.sh"]
