from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from pydantic import BaseModel, EmailStr
from typing import Optional
import logging
from ...shared.config.database import get_db
from ...auth.models.user import User
from ...auth.models.role import Role
from ...system.models.system_settings import SystemSettings
from ...shared.utils.mailer import send_email
from ...shared.utils.sanitization import sanitize_text_for_html
logger = logging.getLogger(__name__)
router = APIRouter(prefix='/contact', tags=['contact'])

class ContactForm(BaseModel):
    name: str
    email: EmailStr
    subject: str
    message: str
    phone: Optional[str] = None

def get_admin_email(db: Session) -> str:
    company_email_setting = db.query(SystemSettings).filter(SystemSettings.key == 'company_email').first()
    if company_email_setting and company_email_setting.value:
        return company_email_setting.value
    admin_email_setting = db.query(SystemSettings).filter(SystemSettings.key == 'admin_email').first()
    if admin_email_setting and admin_email_setting.value:
        return admin_email_setting.value
    admin_role = db.query(Role).filter(Role.name == 'admin').first()
    if admin_role:
        admin_user = db.query(User).filter(User.role_id == admin_role.id, User.is_active == True).first()
        if admin_user:
            return admin_user.email
    from ...shared.config.settings import settings
    if settings.SMTP_FROM_EMAIL:
        return settings.SMTP_FROM_EMAIL
    raise HTTPException(status_code=500, detail='Admin email not configured. Please set company_email in system settings or ensure an admin user exists.')

@router.post('/submit')
async def submit_contact_form(contact_data: ContactForm, db: Session=Depends(get_db)):
    try:
        admin_email = get_admin_email(db)
        subject = f'Contact Form: {contact_data.subject}'
        html_body = f
        text_body = f
        await send_email(to=admin_email, subject=subject, html=html_body, text=text_body)
        logger.info(f'Contact form submitted successfully. Email sent to {admin_email}')
        return {'status': 'success', 'message': 'Thank you for contacting us! We will get back to you soon.'}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f'Failed to submit contact form: {type(e).__name__}: {str(e)}', exc_info=True)
        raise HTTPException(status_code=500, detail='Failed to submit contact form. Please try again later.')