#!/bin/bash
# Script de despliegue para k3s
# Uso: ./deploy.sh [build|deploy|status|logs|delete]

set -e

NAMESPACE="student-enrollment"
REGISTRY="${REGISTRY:-localhost:5000}"
VERSION="${VERSION:-latest}"

# Colores
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info() { echo -e "${GREEN}[INFO]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

build_images() {
    log_info "Building Docker images..."

    cd "$(dirname "$0")/../.."

    # Build API
    log_info "Building API image..."
    docker build -t ${REGISTRY}/student-enrollment/api:${VERSION} \
        -f deploy/docker/Dockerfile.api .

    # Build Frontend
    log_info "Building Frontend image..."
    docker build -t ${REGISTRY}/student-enrollment/frontend:${VERSION} \
        -f deploy/docker/Dockerfile.frontend .

    log_info "Images built successfully"

    # Push si hay registry
    if [[ "$REGISTRY" != "localhost:5000" ]]; then
        log_info "Pushing images to registry..."
        docker push ${REGISTRY}/student-enrollment/api:${VERSION}
        docker push ${REGISTRY}/student-enrollment/frontend:${VERSION}
    fi
}

deploy() {
    log_info "Deploying to k3s..."

    cd "$(dirname "$0")"

    # Aplicar con kustomize
    kubectl apply -k .

    log_info "Waiting for deployments..."
    kubectl rollout status deployment/sqlserver -n ${NAMESPACE} --timeout=120s || true
    kubectl rollout status deployment/student-api -n ${NAMESPACE} --timeout=60s
    kubectl rollout status deployment/student-frontend -n ${NAMESPACE} --timeout=60s

    log_info "Deployment complete!"
    status
}

status() {
    log_info "Cluster status:"
    echo ""
    kubectl get all -n ${NAMESPACE}
    echo ""
    kubectl get ingress -n ${NAMESPACE}
    echo ""
    log_info "Pod status:"
    kubectl get pods -n ${NAMESPACE} -o wide
}

logs() {
    local component="${1:-api}"
    case $component in
        api)
            kubectl logs -n ${NAMESPACE} -l app=student-api -f --tail=100
            ;;
        frontend)
            kubectl logs -n ${NAMESPACE} -l app=student-frontend -f --tail=100
            ;;
        db|sqlserver)
            kubectl logs -n ${NAMESPACE} -l app=sqlserver -f --tail=100
            ;;
        *)
            log_error "Unknown component: $component"
            echo "Usage: $0 logs [api|frontend|db]"
            ;;
    esac
}

delete() {
    log_warn "Deleting deployment..."
    read -p "Are you sure? (y/N) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        kubectl delete -k . || true
        kubectl delete namespace ${NAMESPACE} || true
        log_info "Deployment deleted"
    else
        log_info "Cancelled"
    fi
}

port_forward() {
    log_info "Port forwarding..."
    log_info "Frontend: http://localhost:8080"
    log_info "API: http://localhost:5000/graphql"

    kubectl port-forward -n ${NAMESPACE} svc/student-frontend 8080:80 &
    kubectl port-forward -n ${NAMESPACE} svc/student-api 5000:5000 &

    wait
}

case "${1:-help}" in
    build)
        build_images
        ;;
    deploy)
        deploy
        ;;
    status)
        status
        ;;
    logs)
        logs "$2"
        ;;
    delete)
        delete
        ;;
    forward|port-forward)
        port_forward
        ;;
    all)
        build_images
        deploy
        ;;
    *)
        echo "Student Enrollment - k3s Deployment Script"
        echo ""
        echo "Usage: $0 <command>"
        echo ""
        echo "Commands:"
        echo "  build       Build Docker images"
        echo "  deploy      Deploy to k3s cluster"
        echo "  status      Show deployment status"
        echo "  logs        Show logs (api|frontend|db)"
        echo "  forward     Port forward services"
        echo "  delete      Delete deployment"
        echo "  all         Build and deploy"
        echo ""
        echo "Environment variables:"
        echo "  REGISTRY    Docker registry (default: localhost:5000)"
        echo "  VERSION     Image version tag (default: latest)"
        ;;
esac
