#!/bin/bash

# Email Deliverability Testing Script
#
# Tests email deliverability for the ShowPrima domain:
# - SPF record validation
# - DKIM signing verification
# - DMARC policy verification
# - Mail-tester.com integration
# - Inbox placement testing
#
# Usage:
#   ./scripts/test-email-deliverability.sh
#   ./scripts/test-email-deliverability.sh --help
#
# Exit Codes:
#   0 - All checks passed
#   1 - Critical issues found (missing DNS records, etc.)
#
# Story: 1.5 - Email Deliverability Testing & Monitoring
# Epic: 1 - Email System & Campaign Management

# Load atomic functions
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/_deploy-atoms.sh"

# ==============================================================================
# CONFIGURATION
# ==============================================================================

# Get domain from .env file
if [ -f "$SCRIPT_DIR/../.env" ]; then
    MAIL_FROM_ADDRESS=$(grep "^MAIL_FROM_ADDRESS=" "$SCRIPT_DIR/../.env" | cut -d= -f2-)
    DOMAIN=$(echo "$MAIL_FROM_ADDRESS" | cut -d@ -f2)
else
    log_error ".env file not found"
    exit 1
fi

# If domain not found in .env, use default
if [ -z "$DOMAIN" ]; then
    DOMAIN="globalgalashow.com"
    log_warning "MAIL_FROM_ADDRESS not in .env, using default: $DOMAIN"
fi

CRITICAL_ISSUES=0
WARNINGS=0

# ==============================================================================
# FUNCTIONS
# ==============================================================================

# Display usage instructions
show_help() {
    cat << EOF
Email Deliverability Testing Script

USAGE:
    ./scripts/test-email-deliverability.sh [OPTIONS]

OPTIONS:
    --help          Show this help message

DESCRIPTION:
    Tests email deliverability for domain: $DOMAIN

    Checks performed:
    - SPF record validation
    - DKIM record verification
    - DMARC policy verification

    Target Score: 9/10+ on mail-tester.com

EXAMPLES:
    # Run all checks
    ./scripts/test-email-deliverability.sh

    # Show help
    ./scripts/test-email-deliverability.sh --help

EXIT CODES:
    0 - All checks passed (deliverability OK)
    1 - Critical issues found (deliverability at risk)

For manual mail-tester.com testing:
    1. Visit https://www.mail-tester.com
    2. Get unique test email address
    3. Send test email from Laravel:
       php artisan tinker
       >>> Mail::to('test-xxxxx@mail-tester.com')->send(new \\App\\Mail\\WelcomeUserMail(\\App\\User::first()));
    4. Check score on mail-tester.com (target: 9/10+)

EOF
}

# Check SPF record
check_spf_record() {
    log_info "Checking SPF record for $DOMAIN..."

    if ! command_exists dig; then
        log_error "dig command not found. Install dnsutils: apt-get install dnsutils"
        ((CRITICAL_ISSUES++))
        return 1
    fi

    local spf_record=$(dig TXT "$DOMAIN" +short | grep "v=spf1")

    if [ -n "$spf_record" ]; then
        log_success "SPF record found: $spf_record"

        # Check if SPF includes common issues
        if echo "$spf_record" | grep -q "~all"; then
            log_info "SPF uses soft fail (~all) - recommended for testing"
        elif echo "$spf_record" | grep -q "-all"; then
            log_success "SPF uses hard fail (-all) - maximum protection"
        else
            log_warning "SPF doesn't end with ~all or -all"
            ((WARNINGS++))
        fi
    else
        log_error "SPF record NOT found"
        log_error "Without SPF, emails may be marked as spam"
        log_info "Example SPF record: v=spf1 mx a ~all"
        ((CRITICAL_ISSUES++))
        return 1
    fi
}

# Check DKIM record
check_dkim_signing() {
    log_info "Checking DKIM record for $DOMAIN..."

    # Check common DKIM selector (default._domainkey)
    local dkim_record=$(dig TXT "default._domainkey.$DOMAIN" +short)

    if [ -n "$dkim_record" ]; then
        log_success "DKIM record found: default._domainkey.$DOMAIN"

        # Check if it's a valid DKIM record
        if echo "$dkim_record" | grep -q "v=DKIM1"; then
            log_success "Valid DKIM record (v=DKIM1)"
        else
            log_warning "DKIM record format may be invalid"
            ((WARNINGS++))
        fi
    else
        log_warning "DKIM record NOT found (checked default._domainkey)"
        log_info "DKIM signing may be handled by SMTP provider (e.g., Mailpit, SendGrid)"
        log_info "If using external SMTP, verify DKIM with provider"
        ((WARNINGS++))
    fi
}

# Check DMARC record
check_dmarc_record() {
    log_info "Checking DMARC record for $DOMAIN..."

    local dmarc_record=$(dig TXT "_dmarc.$DOMAIN" +short)

    if [ -n "$dmarc_record" ]; then
        log_success "DMARC record found: $dmarc_record"

        # Check DMARC policy
        if echo "$dmarc_record" | grep -q "p=reject"; then
            log_success "DMARC policy: reject (strict)"
        elif echo "$dmarc_record" | grep -q "p=quarantine"; then
            log_success "DMARC policy: quarantine (recommended)"
        elif echo "$dmarc_record" | grep -q "p=none"; then
            log_warning "DMARC policy: none (monitoring only)"
            ((WARNINGS++))
        fi
    else
        log_error "DMARC record NOT found"
        log_error "DMARC is REQUIRED by Gmail/Yahoo for bulk senders"
        log_info "Example DMARC record: v=DMARC1; p=quarantine; rua=mailto:dmarc@$DOMAIN"
        ((CRITICAL_ISSUES++))
        return 1
    fi
}

# Display mail-tester instructions
show_mail_tester_instructions() {
    log_section "Mail-Tester.com Testing"

    log_info "Mail-tester.com provides a deliverability score (0-10)"
    log_info "Target score: 9/10+ (10/10 ideal)"
    echo ""
    log_info "Manual Testing Steps:"
    echo "  1. Visit: https://www.mail-tester.com"
    echo "  2. Copy the unique test email address"
    echo "  3. Send test email from Laravel:"
    echo ""
    echo "     php artisan tinker"
    echo "     >>> \$user = \\App\\User::first();"
    echo "     >>> Mail::to('test-xxxxx@mail-tester.com')->send(new \\App\\Mail\\WelcomeUserMail(\$user));"
    echo ""
    echo "  4. Return to mail-tester.com and click 'Then check your score'"
    echo "  5. Review results and fix any issues"
    echo ""
    log_info "Common issues that reduce score:"
    echo "  - Missing SPF/DKIM/DMARC records (-1 to -3 points each)"
    echo "  - Blacklisted IP address (-2 to -5 points)"
    echo "  - Spam trigger words (-1 to -2 points)"
    echo "  - Missing unsubscribe link (-1 point)"
    echo ""
}

# Display results summary
display_results() {
    log_section "Deliverability Test Results"

    if [ $CRITICAL_ISSUES -eq 0 ] && [ $WARNINGS -eq 0 ]; then
        log_success "All checks PASSED - Email deliverability is GOOD"
        log_success "Domain: $DOMAIN"
        echo ""
        log_info "Next steps:"
        echo "  - Test with mail-tester.com (see instructions above)"
        echo "  - Monitor deliverability with: ./scripts/cron/email-deliverability-monitor.sh"
        echo ""
        return 0
    elif [ $CRITICAL_ISSUES -eq 0 ]; then
        log_warning "$WARNINGS warning(s) found - Email deliverability is OK"
        log_warning "Consider addressing warnings to improve deliverability"
        echo ""
        return 0
    else
        log_error "$CRITICAL_ISSUES critical issue(s) found"
        log_error "Email deliverability is AT RISK"
        echo ""
        log_error "Action required:"
        echo "  - Fix missing DNS records (SPF/DKIM/DMARC)"
        echo "  - See docs/EMAIL_DELIVERABILITY_CHECKLIST.md for setup guide"
        echo ""
        return 1
    fi
}

# ==============================================================================
# MAIN EXECUTION
# ==============================================================================

main() {
    # Parse arguments
    if [ "$1" == "--help" ] || [ "$1" == "-h" ]; then
        show_help
        exit 0
    fi

    log_section "Email Deliverability Testing"
    log_info "Domain: $DOMAIN"
    echo ""

    # Run DNS checks
    check_spf_record
    echo ""

    check_dkim_signing
    echo ""

    check_dmarc_record
    echo ""

    # Show mail-tester instructions
    show_mail_tester_instructions

    # Display results
    display_results
    local exit_code=$?

    exit $exit_code
}

# Run main function
main "$@"
