#!/bin/bash

# ═══════════════════════════════════════════════════════════════
# SMTP API Service - سكريبت التثبيت التلقائي
# ═══════════════════════════════════════════════════════════════

set -e  # إيقاف السكريبت عند أي خطأ

# الألوان
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# المتغيرات
PROJECT_DIR="/opt/smtp-api-service"
DOMAIN=""
EMAIL=""

# دوال المساعدة
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

# التحقق من root
if [ "$EUID" -ne 0 ]; then
    print_error "هذا السكريبت يجب تشغيله كـ root"
    print_status "استخدم: sudo bash install.sh"
    exit 1
fi

# عرض الترحيب
clear
echo "═══════════════════════════════════════════════════════════════"
echo "           SMTP API Service - سكريبت التثبيت التلقائي"
echo "═══════════════════════════════════════════════════════════════"
echo ""

# جمع المعلومات
echo "أدخل المعلومات المطلوبة:"
echo "─────────────────────────"
read -p "اسم النطاق (Domain) مثال: api.example.com: " DOMAIN
read -p "بريدك الإلكتروني (لشهادة SSL): " EMAIL

echo ""
print_status "بدء التثبيت..."
echo ""

# ═══════════════════════════════════════════════════════════════
# الخطوة 1: تحديث النظام
# ═══════════════════════════════════════════════════════════════
print_status "تحديث النظام..."
apt update -qq
apt upgrade -y -qq
print_success "تم تحديث النظام"

# ═══════════════════════════════════════════════════════════════
# الخطوة 2: تثبيت المتطلبات
# ═══════════════════════════════════════════════════════════════
print_status "تثبيت المتطلبات..."
apt install -y -qq \
    python3 \
    python3-pip \
    python3-venv \
    nginx \
    git \
    curl \
    wget \
    unzip \
    certbot \
    python3-certbot-nginx \
    ufw

print_success "تم تثبيت المتطلبات"

# ═══════════════════════════════════════════════════════════════
# الخطوة 3: إنشاء مجلد المشروع
# ═══════════════════════════════════════════════════════════════
print_status "إعداد مجلد المشروع..."

if [ -d "$PROJECT_DIR" ]; then
    print_warning "مجلد المشروع موجود. هل تريد استبداله؟ (y/n)"
    read -r response
    if [[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]]; then
        rm -rf "$PROJECT_DIR"
    else
        print_error "تم إلغاء التثبيت"
        exit 1
    fi
fi

mkdir -p "$PROJECT_DIR"
cd "$PROJECT_DIR"

# ═══════════════════════════════════════════════════════════════
# الخطوة 4: نسخ ملفات المشروع
# ═══════════════════════════════════════════════════════════════
print_status "نسخ ملفات المشروع..."

# إنشاء هيكل المشروع
mkdir -p backend frontend

# إنشاء ملفات Backend
print_status "إنشاء ملفات Backend..."

# main.py
cat > backend/main.py << 'EOF'
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from datetime import timedelta
import uvicorn

from config import get_settings
from database import create_tables, get_db, User
from schemas import UserCreate, UserLogin, UserResponse, Token
from auth import authenticate_user, create_access_token, get_password_hash, get_current_active_user
from api_key_service import create_api_key, get_user_api_keys, revoke_api_key, delete_api_key, reactivate_api_key, get_api_key_stats
from email_service import EmailService

settings = get_settings()

app = FastAPI(
    title=settings.APP_NAME,
    description="SMTP API Service - Send emails via REST API",
    version=settings.APP_VERSION,
    docs_url="/docs",
    redoc_url="/redoc"
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.on_event("startup")
async def startup_event():
    create_tables()
    print(f"🚀 {settings.APP_NAME} started!")

@app.get("/")
async def root():
    return {"name": settings.APP_NAME, "version": settings.APP_VERSION, "status": "running"}

@app.get("/health")
async def health_check():
    return {"status": "healthy"}

@app.post("/api/v1/auth/register", response_model=UserResponse)
async def register(user_data: UserCreate, db: Session = Depends(get_db)):
    existing_user = db.query(User).filter(
        (User.email == user_data.email) | (User.username == user_data.username)
    ).first()
    
    if existing_user:
        raise HTTPException(status_code=400, detail="User already exists")
    
    hashed_password = get_password_hash(user_data.password)
    db_user = User(
        email=user_data.email,
        username=user_data.username,
        hashed_password=hashed_password,
        full_name=user_data.full_name,
        is_active=True
    )
    
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

@app.post("/api/v1/auth/login", response_model=Token)
async def login(credentials: UserLogin, db: Session = Depends(get_db)):
    user = authenticate_user(db, credentials.username, credentials.password)
    if not user:
        raise HTTPException(status_code=401, detail="Incorrect credentials")
    
    access_token = create_access_token(data={"sub": user.username})
    return {"access_token": access_token, "token_type": "bearer", "expires_in": 1800}

@app.get("/api/v1/auth/me", response_model=UserResponse)
async def get_me(current_user: User = Depends(get_current_active_user)):
    return current_user

# API Keys
@app.post("/api/v1/api-keys")
async def create_new_api_key(key_data, current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db)):
    from pydantic import BaseModel
    class ApiKeyCreate(BaseModel):
        name: str
    api_key = create_api_key(db, current_user.id, key_data.name)
    return api_key

@app.get("/api/v1/api-keys")
async def list_api_keys(current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db)):
    return get_user_api_keys(db, current_user.id)

# SMTP Configs
@app.get("/api/v1/smtp-configs")
async def list_smtp_configs(current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db)):
    email_service = EmailService(db)
    return email_service.get_all_user_smtp_configs(current_user.id)

# Email
@app.post("/api/v1/emails/send")
async def send_email(email_data, current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db)):
    email_service = EmailService(db)
    return email_service.send_email(current_user.id, email_data)

# Public API
@app.post("/api/v1/public/send-email")
async def public_send_email(email_data, db: Session = Depends(get_db)):
    from api_key_service import validate_api_key
    api_key_record = validate_api_key(db, email_data.api_key)
    if not api_key_record:
        raise HTTPException(status_code=401, detail="Invalid API key")
    
    email_service = EmailService(db)
    return email_service.send_email_with_api_key(api_key_record, email_data.dict(exclude={'api_key'}))

# Dashboard
@app.get("/api/v1/dashboard/stats")
async def get_dashboard_stats(current_user: User = Depends(get_current_active_user), db: Session = Depends(get_db)):
    email_service = EmailService(db)
    email_stats = email_service.get_email_stats(current_user.id)
    api_stats = get_api_key_stats(db, current_user.id)
    
    return {
        "total_emails_sent": email_stats["total_sent"],
        "emails_sent_today": email_stats["today_sent"],
        "active_api_keys": api_stats["active_keys"],
        "smtp_configs": len(current_user.smtp_configs),
        "recent_emails": email_service.get_email_logs(current_user.id, 10)
    }

if __name__ == "__main__":
    uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=False)
EOF

# database.py
cat > backend/database.py << 'EOF'
from sqlalchemy import create_engine, Column, Integer, String, Boolean, DateTime, Text, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from datetime import datetime

DATABASE_URL = "sqlite:///./smtp_api.db"

engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

class User(Base):
    __tablename__ = "users"
    
    id = Column(Integer, primary_key=True, index=True)
    email = Column(String, unique=True, index=True)
    username = Column(String, unique=True, index=True)
    hashed_password = Column(String)
    full_name = Column(String)
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    
    api_keys = relationship("ApiKey", back_populates="user", cascade="all, delete-orphan")
    smtp_configs = relationship("SMTPConfig", back_populates="user", cascade="all, delete-orphan")
    email_logs = relationship("EmailLog", back_populates="user", cascade="all, delete-orphan")

class ApiKey(Base):
    __tablename__ = "api_keys"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"))
    key_name = Column(String)
    api_key = Column(String, unique=True, index=True)
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    last_used_at = Column(DateTime, nullable=True)
    usage_count = Column(Integer, default=0)
    
    user = relationship("User", back_populates="api_keys")

class SMTPConfig(Base):
    __tablename__ = "smtp_configs"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"))
    name = Column(String)
    host = Column(String)
    port = Column(Integer)
    username = Column(String)
    password = Column(String)
    use_tls = Column(Boolean, default=True)
    is_default = Column(Boolean, default=False)
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    
    user = relationship("User", back_populates="smtp_configs")

class EmailLog(Base):
    __tablename__ = "email_logs"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"))
    from_email = Column(String)
    to_email = Column(String)
    subject = Column(String)
    status = Column(String)
    error_message = Column(Text, nullable=True)
    sent_at = Column(DateTime, default=datetime.utcnow)
    
    user = relationship("User", back_populates="email_logs")

def create_tables():
    Base.metadata.create_all(bind=engine)

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
EOF

# auth.py
cat > backend/auth.py << 'EOF'
from datetime import datetime, timedelta
from jose import JWTError, jwt
from passlib.context import CryptContext
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from database import get_db, User

SECRET_KEY = "your-secret-key-change-in-production-32-chars-long"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
security = HTTPBearer()

def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)

def get_password_hash(password):
    return pwd_context.hash(password)

def create_access_token(data: dict):
    to_encode = data.copy()
    expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)

def decode_token(token: str):
    try:
        return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    except JWTError:
        return None

async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security), db: Session = Depends(get_db)):
    payload = decode_token(credentials.credentials)
    if payload is None:
        raise HTTPException(status_code=401, detail="Invalid credentials")
    
    username = payload.get("sub")
    user = db.query(User).filter(User.username == username).first()
    if user is None:
        raise HTTPException(status_code=401, detail="User not found")
    
    return user

async def get_current_active_user(current_user: User = Depends(get_current_user)):
    if not current_user.is_active:
        raise HTTPException(status_code=400, detail="Inactive user")
    return current_user

def authenticate_user(db: Session, username: str, password: str):
    user = db.query(User).filter(User.username == username).first()
    if not user or not verify_password(password, user.hashed_password):
        return None
    return user
EOF

# config.py
cat > backend/config.py << 'EOF'
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    APP_NAME: str = "SMTP API Service"
    APP_VERSION: str = "1.0.0"
    DEBUG: bool = False
    SECRET_KEY: str = "your-secret-key-change-in-production"
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
    DATABASE_URL: str = "sqlite:///./smtp_api.db"
    API_V1_PREFIX: str = "/api/v1"
    
    class Config:
        env_file = ".env"

def get_settings():
    return Settings()
EOF

# schemas.py
cat > backend/schemas.py << 'EOF'
from pydantic import BaseModel, EmailStr
from typing import Optional
from datetime import datetime

class UserBase(BaseModel):
    email: EmailStr
    username: str
    full_name: Optional[str] = None

class UserCreate(UserBase):
    password: str

class UserLogin(BaseModel):
    username: str
    password: str

class UserResponse(UserBase):
    id: int
    is_active: bool
    created_at: datetime
    
    class Config:
        from_attributes = True

class Token(BaseModel):
    access_token: str
    token_type: str = "bearer"
    expires_in: int
EOF

# api_key_service.py
cat > backend/api_key_service.py << 'EOF'
import secrets
import string
from sqlalchemy.orm import Session
from database import ApiKey
from datetime import datetime

def generate_api_key(length: int = 32) -> str:
    alphabet = string.ascii_letters + string.digits
    api_key = ''.join(secrets.choice(alphabet) for _ in range(length))
    return f"smtp_{api_key}"

def create_api_key(db: Session, user_id: int, key_name: str):
    while True:
        api_key = generate_api_key()
        existing = db.query(ApiKey).filter(ApiKey.api_key == api_key).first()
        if not existing:
            break
    
    db_api_key = ApiKey(
        user_id=user_id,
        key_name=key_name,
        api_key=api_key,
        is_active=True,
        usage_count=0
    )
    db.add(db_api_key)
    db.commit()
    db.refresh(db_api_key)
    return db_api_key

def get_user_api_keys(db: Session, user_id: int):
    return db.query(ApiKey).filter(ApiKey.user_id == user_id).all()

def revoke_api_key(db: Session, key_id: int, user_id: int):
    api_key = db.query(ApiKey).filter(ApiKey.id == key_id, ApiKey.user_id == user_id).first()
    if api_key:
        api_key.is_active = False
        db.commit()
        return True
    return False

def reactivate_api_key(db: Session, key_id: int, user_id: int):
    api_key = db.query(ApiKey).filter(ApiKey.id == key_id, ApiKey.user_id == user_id).first()
    if api_key:
        api_key.is_active = True
        db.commit()
        return True
    return False

def delete_api_key(db: Session, key_id: int, user_id: int):
    api_key = db.query(ApiKey).filter(ApiKey.id == key_id, ApiKey.user_id == user_id).first()
    if api_key:
        db.delete(api_key)
        db.commit()
        return True
    return False

def validate_api_key(db: Session, api_key: str):
    key_record = db.query(ApiKey).filter(ApiKey.api_key == api_key, ApiKey.is_active == True).first()
    if key_record:
        key_record.usage_count += 1
        key_record.last_used_at = datetime.utcnow()
        db.commit()
    return key_record

def get_api_key_stats(db: Session, user_id: int):
    total = db.query(ApiKey).filter(ApiKey.user_id == user_id).count()
    active = db.query(ApiKey).filter(ApiKey.user_id == user_id, ApiKey.is_active == True).count()
    return {"total_keys": total, "active_keys": active}
EOF

# email_service.py
cat > backend/email_service.py << 'EOF'
import smtplib
import ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from sqlalchemy.orm import Session
from database import SMTPConfig, EmailLog
from datetime import datetime

class EmailService:
    def __init__(self, db: Session):
        self.db = db
    
    def get_user_smtp_config(self, user_id: int):
        return self.db.query(SMTPConfig).filter(
            SMTPConfig.user_id == user_id,
            SMTPConfig.is_default == True,
            SMTPConfig.is_active == True
        ).first()
    
    def get_all_user_smtp_configs(self, user_id: int):
        return self.db.query(SMTPConfig).filter(SMTPConfig.user_id == user_id).all()
    
    def send_email(self, user_id: int, email_data):
        smtp_config = self.get_user_smtp_config(user_id)
        
        if not smtp_config:
            return {"success": False, "message": "No SMTP configuration found"}
        
        try:
            msg = MIMEMultipart('alternative')
            msg['Subject'] = email_data.subject
            msg['From'] = smtp_config.username
            msg['To'] = email_data.to_email
            
            content_type = 'html' if getattr(email_data, 'is_html', False) else 'plain'
            msg.attach(MIMEText(email_data.body, content_type, 'utf-8'))
            
            context = ssl.create_default_context()
            with smtplib.SMTP(smtp_config.host, smtp_config.port) as server:
                if smtp_config.use_tls:
                    server.starttls(context=context)
                server.login(smtp_config.username, smtp_config.password)
                server.send_message(msg)
            
            self._log_email(user_id, None, smtp_config.username, email_data.to_email, email_data.subject, "sent", None)
            return {"success": True, "message": "Email sent successfully"}
            
        except Exception as e:
            self._log_email(user_id, None, smtp_config.username, email_data.to_email, email_data.subject, "failed", str(e))
            return {"success": False, "message": f"Failed to send email: {str(e)}"}
    
    def send_email_with_api_key(self, api_key_record, email_data: dict):
        user_id = api_key_record.user_id
        smtp_config = self.get_user_smtp_config(user_id)
        
        if not smtp_config:
            return {"success": False, "message": "No SMTP configuration"}
        
        try:
            msg = MIMEMultipart('alternative')
            msg['Subject'] = email_data['subject']
            msg['From'] = email_data.get('from_name', smtp_config.username)
            msg['To'] = email_data['to_email']
            
            is_html = email_data.get('is_html', False)
            msg.attach(MIMEText(email_data['body'], 'html' if is_html else 'plain', 'utf-8'))
            
            context = ssl.create_default_context()
            with smtplib.SMTP(smtp_config.host, smtp_config.port) as server:
                if smtp_config.use_tls:
                    server.starttls(context=context)
                server.login(smtp_config.username, smtp_config.password)
                server.send_message(msg)
            
            self._log_email(user_id, api_key_record.id, smtp_config.username, email_data['to_email'], email_data['subject'], "sent", None)
            return {"success": True, "message": "Email sent successfully"}
            
        except Exception as e:
            self._log_email(user_id, api_key_record.id, smtp_config.username, email_data['to_email'], email_data['subject'], "failed", str(e))
            return {"success": False, "message": str(e)}
    
    def _log_email(self, user_id, api_key_id, from_email, to_email, subject, status, error):
        log = EmailLog(
            user_id=user_id,
            api_key_id=api_key_id,
            from_email=from_email,
            to_email=to_email,
            subject=subject,
            status=status,
            error_message=error
        )
        self.db.add(log)
        self.db.commit()
    
    def get_email_logs(self, user_id: int, limit: int = 50):
        return self.db.query(EmailLog).filter(
            EmailLog.user_id == user_id
        ).order_by(EmailLog.sent_at.desc()).limit(limit).all()
    
    def get_email_stats(self, user_id: int):
        total_sent = self.db.query(EmailLog).filter(EmailLog.user_id == user_id, EmailLog.status == "sent").count()
        total_failed = self.db.query(EmailLog).filter(EmailLog.user_id == user_id, EmailLog.status == "failed").count()
        today = datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0)
        today_sent = self.db.query(EmailLog).filter(EmailLog.user_id == user_id, EmailLog.status == "sent", EmailLog.sent_at >= today).count()
        
        return {
            "total_sent": total_sent,
            "total_failed": total_failed,
            "today_sent": today_sent,
            "success_rate": round((total_sent / (total_sent + total_failed)) * 100, 2) if (total_sent + total_failed) > 0 else 0
        }
EOF

# requirements.txt
cat > backend/requirements.txt << 'EOF'
fastapi==0.109.0
uvicorn[standard]==0.27.0
sqlalchemy==2.0.25
pydantic==2.5.3
pydantic-settings==2.1.0
python-jose[cryptography]==3.3.0
passlib[bcrypt]==1.7.4
python-multipart==0.0.6
email-validator==2.1.0
EOF

print_success "تم إنشاء ملفات Backend"

# ═══════════════════════════════════════════════════════════════
# الخطوة 5: إنشاء Frontend
# ═══════════════════════════════════════════════════════════════
print_status "إنشاء ملفات Frontend..."

# نسخ ملف index.html الموجود أو إنشاء واحد جديد
if [ -f "/tmp/index.html" ]; then
    cp /tmp/index.html frontend/index.html
else
    # إنشاء Frontend بسيط
    cat > frontend/index.html << 'HTMLEOF'
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SMTP API Service</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>@import url('https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap'); body { font-family: 'Cairo', sans-serif; }</style>
</head>
<body class="bg-gray-100">
    <div id="app" class="min-h-screen flex items-center justify-center">
        <div class="text-center">
            <h1 class="text-4xl font-bold text-blue-600 mb-4">SMTP API Service</h1>
            <p class="text-gray-600">الخدمة تعمل بنجاح!</p>
            <div class="mt-8">
                <a href="/docs" class="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition">
                    <i class="fas fa-book ml-2"></i>API Documentation
                </a>
            </div>
        </div>
    </div>
</body>
</html>
HTMLEOF
fi

print_success "تم إنشاء ملفات Frontend"

# ═══════════════════════════════════════════════════════════════
# الخطوة 6: إعداد البيئة الافتراضية
# ═══════════════════════════════════════════════════════════════
print_status "إعداد البيئة الافتراضية..."

cd "$PROJECT_DIR/backend"
python3 -m venv venv
source venv/bin/activate
pip install --upgrade pip -q
pip install -r requirements.txt -q

print_success "تم تثبيت المتطلبات"

# ═══════════════════════════════════════════════════════════════
# الخطوة 7: إعداد Nginx
# ═══════════════════════════════════════════════════════════════
print_status "إعداد Nginx..."

cat > /etc/nginx/sites-available/smtp-api << NGINXCONF
server {
    listen 80;
    server_name $DOMAIN;

    location / {
        root $PROJECT_DIR/frontend;
        index index.html;
        try_files \$uri \$uri/ /index.html;
    }

    location /api/ {
        proxy_pass http://127.0.0.1:8000/api/;
        proxy_http_version 1.1;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

    location /docs {
        proxy_pass http://127.0.0.1:8000/docs;
        proxy_set_header Host \$host;
    }

    location /redoc {
        proxy_pass http://127.0.0.1:8000/redoc;
        proxy_set_header Host \$host;
    }
}
NGINXCONF

ln -sf /etc/nginx/sites-available/smtp-api /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
nginx -t
systemctl restart nginx

print_success "تم إعداد Nginx"

# ═══════════════════════════════════════════════════════════════
# الخطوة 8: إعداد SSL
# ═══════════════════════════════════════════════════════════════
print_status "إعداد شهادة SSL..."

certbot --nginx -d "$DOMAIN" --non-interactive --agree-tos -m "$EMAIL" --redirect 2>/dev/null || {
    print_warning "لم يتم الحصول على SSL تلقائياً. يمكنك تشغيل 'certbot --nginx' يدوياً لاحقاً"
}

# ═══════════════════════════════════════════════════════════════
# الخطوة 9: إعداد systemd service
# ═══════════════════════════════════════════════════════════════
print_status "إعداد خدمة systemd..."

cat > /etc/systemd/system/smtp-api.service << SERVICECONF
[Unit]
Description=SMTP API Service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=$PROJECT_DIR/backend
Environment="PATH=$PROJECT_DIR/backend/venv/bin"
ExecStart=$PROJECT_DIR/backend/venv/bin/uvicorn main:app --host 127.0.0.1 --port 8000 --workers 2
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
SERVICECONF

systemctl daemon-reload
systemctl enable smtp-api
systemctl start smtp-api

print_success "تم إعداد الخدمة"

# ═══════════════════════════════════════════════════════════════
# الخطوة 10: إعداد الجدار الناري
# ═══════════════════════════════════════════════════════════════
print_status "إعداد جدار الحماية..."

ufw default deny incoming
ufw default allow outgoing
ufw allow ssh
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable

print_success "تم إعداد الجدار الناري"

# ═══════════════════════════════════════════════════════════════
# الانتهاء
# ═══════════════════════════════════════════════════════════════
echo ""
echo "═══════════════════════════════════════════════════════════════"
echo "           ✅ تم التثبيت بنجاح!"
echo "═══════════════════════════════════════════════════════════════"
echo ""
echo "📌 روابط مهمة:"
echo "   • الموقع: https://$DOMAIN"
echo "   • API Docs: https://$DOMAIN/docs"
echo "   • API Base: https://$DOMAIN/api/v1"
echo ""
echo "📌 أوامر مفيدة:"
echo "   • عرض السجلات: sudo journalctl -u smtp-api -f"
echo "   • إعادة تشغيل: sudo systemctl restart smtp-api"
echo "   • حالة الخدمة: sudo systemctl status smtp-api"
echo ""
echo "═══════════════════════════════════════════════════════════════"
