from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from datetime import datetime
from typing import List, Optional
from app.db.session import get_db
from app.db.models import User
from app.api.deps import get_current_user
from pydantic import BaseModel

router = APIRouter(prefix="/notification-settings", tags=["notification-settings"])


class MetricAlert(BaseModel):
    metric: str  # "delivery_rate", "open_rate", "click_rate"
    threshold: float  # threshold value
    operator: str  # "below", "above", "equals"
    enabled: bool = True


class NotificationSettings(BaseModel):
    email_alerts: bool = True
    metric_alerts: List[MetricAlert] = []
    weekly_report: bool = False
    daily_summary: bool = False


class NotificationSettingsOut(NotificationSettings):
    id: int
    tenant_id: int
    created_at: datetime
    updated_at: datetime

    class Config:
        from_attributes = True


@router.get("", response_model=NotificationSettingsOut)
def get_notification_settings(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
):
    """Get notification settings for the tenant"""
    # For now, return default settings
    # In a full implementation, you'd store these in the database
    return NotificationSettingsOut(
        id=1,
        tenant_id=current_user.tenant_id,
        email_alerts=True,
        metric_alerts=[
            MetricAlert(metric="delivery_rate", threshold=80.0, operator="below", enabled=True),
            MetricAlert(metric="open_rate", threshold=50.0, operator="below", enabled=True),
        ],
        weekly_report=False,
        daily_summary=False,
        created_at=datetime.utcnow(),
        updated_at=datetime.utcnow(),
    )


@router.put("", response_model=NotificationSettingsOut)
def update_notification_settings(
    settings: NotificationSettings,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
):
    """Update notification settings for the tenant"""
    # For now, just return the updated settings
    # In a full implementation, you'd save these to the database
    return NotificationSettingsOut(
        id=1,
        tenant_id=current_user.tenant_id,
        email_alerts=settings.email_alerts,
        metric_alerts=settings.metric_alerts,
        weekly_report=settings.weekly_report,
        daily_summary=settings.daily_summary,
        created_at=datetime.utcnow(),
        updated_at=datetime.utcnow(),
    )


@router.post("/test-alert")
def test_alert(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db),
):
    """Send a test alert to verify notification settings"""
    # In a full implementation, you'd send an actual email/notification
    return {"message": "Test alert sent successfully", "status": "success"}
