#!/bin/bash
# BMC Hub - Production Deployment Script
# Dette script automatiserer download af nødvendige filer fra Gitea

set -e  # Exit on error

# Farver til output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check om .env eksisterer
if [ ! -f .env ]; then
    echo -e "${RED}❌ Fejl: .env fil ikke fundet${NC}"
    echo "Kopier .env.example til .env og udfyld med dine værdier:"
    echo "  cp .env.example .env"
    echo "  nano .env"
    exit 1
fi

# Load environment variables
source .env

# Verificer påkrævede variables
if [ -z "$GITHUB_TOKEN" ] || [ "$GITHUB_TOKEN" == "your_gitea_token_here" ]; then
    echo -e "${RED}❌ Fejl: GITHUB_TOKEN ikke sat i .env${NC}"
    echo "Opret en Personal Access Token på:"
    echo "  https://g.bmcnetworks.dk/user/settings/applications"
    exit 1
fi

if [ -z "$RELEASE_VERSION" ]; then
    echo -e "${RED}❌ Fejl: RELEASE_VERSION ikke sat i .env${NC}"
    exit 1
fi

GITEA_BASE="${GITEA_URL:-https://g.bmcnetworks.dk}"
REPO="${GITHUB_REPO:-ct/bmc_hub}"
VERSION="${RELEASE_VERSION}"

echo -e "${GREEN}🚀 BMC Hub Production Deployment${NC}"
echo -e "Repository: ${REPO}"
echo -e "Version: ${VERSION}"
echo ""

# Download function
download_file() {
    local file=$1
    local output=${2:-$file}
    
    echo -e "${YELLOW}⬇️  Downloader: ${file}${NC}"
    
    if curl -f -H "Authorization: token ${GITHUB_TOKEN}" \
            "${GITEA_BASE}/api/v1/repos/${REPO}/raw/${file}?ref=${VERSION}" \
            -o "${output}" 2>/dev/null; then
        echo -e "${GREEN}✅ Success: ${output}${NC}"
        return 0
    else
        echo -e "${RED}❌ Fejl ved download af ${file}${NC}"
        return 1
    fi
}

# Opret directories
echo -e "${YELLOW}📁 Opretter directories...${NC}"
mkdir -p migrations logs uploads data/invoice_templates

# Download core files
echo -e "\n${YELLOW}📥 Downloader core filer...${NC}"
download_file "docker-compose.prod.yml" "docker-compose.yml"
download_file "Dockerfile"
download_file "requirements.txt"

# Download migrations
echo -e "\n${YELLOW}📥 Downloader migrations...${NC}"

# Liste over alle migrations (i rækkefølge)
MIGRATIONS=(
    "init.sql"
    "002_auth_system.sql"
    "003_extend_customers.sql"
    "004_contacts_relationships.sql"
    "005_vendors.sql"
    "006_settings.sql"
    "007_dev_portal.sql"
    "008_credit_notes.sql"
    "008_supplier_invoices.sql"
    "009_document_extraction.sql"
    "010_supplier_invoice_templates.sql"
    "011_extraction_lines_context.sql"
    "011_quick_analysis.sql"
    "012_own_invoice_filter.sql"
    "012_template_default_category.sql"
    "013_email_system.sql"
    "013_timetracking_module.sql"
    "014_add_contact_user_company.sql"
    "014_economic_customer_number.sql"
    "014_email_workflows.sql"
    "015_bmc_office_subscriptions.sql"
    "023_subscriptions_lock.sql"
    "024_backup_system.sql"
    "025_ticket_module.sql"
    "026_ticket_enhancements.sql"
    "026_ticket_permissions.sql"
    "027_customer_notes.sql"
    "027_tag_system.sql"
    "028_auto_link_tmodule_customers.sql"
    "029_ticket_contacts.sql"
    "030_ticket_contacts_flexible_roles.sql"
    "050_email_activity_log.sql"
)

for migration in "${MIGRATIONS[@]}"; do
    download_file "migrations/${migration}" "migrations/${migration}" || echo -e "${YELLOW}⚠️  Kunne ikke downloade ${migration} (måske findes den ikke i denne version)${NC}"
done

echo -e "\n${GREEN}✅ Download komplet!${NC}"
echo ""
echo -e "${YELLOW}Næste trin:${NC}"
echo "1. Verificer .env filen er korrekt udfyldt"
echo "2. Start services:"
echo -e "   ${GREEN}podman-compose up -d --build${NC}"
echo "3. Check logs:"
echo -e "   ${GREEN}podman-compose logs -f${NC}"
echo "4. Test health endpoint:"
echo -e "   ${GREEN}curl http://localhost:8000/health${NC}"
echo ""
