#!/bin/bash
# Restore Script for WorkRoot Website
# Restores from backup with safety checks

set -e

# Configuration
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
LOG_FILE="$PROJECT_ROOT/backups/restore.log"

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

log() {
    echo "[$(date +"%Y-%m-%d %H:%M:%S")] $1" | tee -a "$LOG_FILE"
}

# Function to list available backups
list_backups() {
    echo -e "${BLUE}Available Backups:${NC}\n"

    echo -e "${YELLOW}Full Backups (Daily):${NC}"
    ls -lht "$PROJECT_ROOT/backups/daily/"*.tar.gz 2>/dev/null | head -n 10 || echo "  No daily backups found"

    echo -e "\n${YELLOW}Weekly Backups:${NC}"
    ls -lht "$PROJECT_ROOT/backups/weekly/"*.tar.gz 2>/dev/null | head -n 5 || echo "  No weekly backups found"

    echo -e "\n${YELLOW}Monthly Backups:${NC}"
    ls -lht "$PROJECT_ROOT/backups/monthly/"*.tar.gz 2>/dev/null | head -n 3 || echo "  No monthly backups found"

    echo -e "\n${YELLOW}Config Backups (Pre-deploy):${NC}"
    ls -lht "$PROJECT_ROOT/backups/pre-deploy/"*.tar.gz 2>/dev/null | head -n 5 || echo "  No config backups found"
}

# Function to verify backup integrity
verify_backup() {
    local backup_file="$1"

    if [ ! -f "$backup_file" ]; then
        echo -e "${RED}ERROR: Backup file not found: $backup_file${NC}"
        return 1
    fi

    echo -e "${YELLOW}Verifying backup integrity...${NC}"
    if tar -tzf "$backup_file" > /dev/null 2>&1; then
        echo -e "${GREEN}✓ Backup integrity verified${NC}"
        return 0
    else
        echo -e "${RED}✗ Backup is corrupted${NC}"
        return 1
    fi
}

# Function to create safety backup before restore
safety_backup() {
    echo -e "${YELLOW}Creating safety backup of current state...${NC}"
    SAFETY_DIR="$PROJECT_ROOT/backups/safety"
    mkdir -p "$SAFETY_DIR"
    SAFETY_FILE="$SAFETY_DIR/pre-restore-$(date +%Y-%m-%d_%H-%M-%S).tar.gz"

    tar -czf "$SAFETY_FILE" \
        --exclude=node_modules \
        --exclude=dist \
        --exclude=.astro \
        --exclude=backups \
        src/ public/ *.config.* package.json .env 2>/dev/null || true

    echo -e "${GREEN}✓ Safety backup created: $SAFETY_FILE${NC}"
}

# Main restore function
restore_backup() {
    local backup_file="$1"
    local restore_path="${2:-$PROJECT_ROOT}"

    log "${BLUE}Starting restore process...${NC}"
    log "Backup file: $backup_file"
    log "Restore path: $restore_path"

    # Verify backup
    verify_backup "$backup_file" || exit 1

    # Show backup contents
    echo -e "\n${YELLOW}Backup contains:${NC}"
    tar -tzf "$backup_file" | head -n 20
    echo "..."

    # Confirm restore
    echo -e "\n${RED}WARNING: This will overwrite current files!${NC}"
    read -p "Continue with restore? (yes/no): " confirm
    if [ "$confirm" != "yes" ]; then
        echo "Restore cancelled"
        exit 0
    fi

    # Create safety backup
    safety_backup

    # Extract backup
    echo -e "\n${YELLOW}Extracting backup...${NC}"
    cd "$restore_path"
    tar -xzf "$backup_file" || {
        echo -e "${RED}ERROR: Restore failed${NC}"
        exit 1
    }

    echo -e "${GREEN}✓ Files extracted successfully${NC}"

    # Verify critical files
    echo -e "\n${YELLOW}Verifying restored files...${NC}"
    CRITICAL_FILES=("src/" "package.json" "astro.config.mjs")
    for file in "${CRITICAL_FILES[@]}"; do
        if [ -e "$file" ]; then
            echo -e "  ${GREEN}✓${NC} $file"
        else
            echo -e "  ${RED}✗${NC} $file (missing)"
        fi
    done

    # Post-restore instructions
    echo -e "\n${GREEN}=== Restore Completed ===${NC}"
    echo -e "\n${YELLOW}Next steps:${NC}"
    echo "1. Verify .env file and update secrets if needed"
    echo "2. Run: npm install"
    echo "3. Run: npm run build"
    echo "4. Run: npm run test"
    echo "5. Check logs for any issues"

    log "${GREEN}Restore completed successfully${NC}"
}

# Main script logic
case "${1:-}" in
    list|--list|-l)
        list_backups
        ;;
    verify|--verify|-v)
        if [ -z "$2" ]; then
            echo "Usage: $0 verify <backup-file>"
            exit 1
        fi
        verify_backup "$2"
        ;;
    *)
        if [ -z "$1" ]; then
            echo -e "${YELLOW}Usage:${NC}"
            echo "  $0 list                    - List available backups"
            echo "  $0 verify <backup-file>    - Verify backup integrity"
            echo "  $0 <backup-file>           - Restore from backup"
            echo ""
            echo -e "${YELLOW}Quick restore from latest:${NC}"
            echo "  $0 backups/daily/latest-full.tar.gz"
            exit 1
        fi
        restore_backup "$1" "$2"
        ;;
esac
