from fastapi import APIRouter, HTTPException, File, UploadFile
from fastapi.responses import FileResponse
from typing import List
from models.schemas import ContactCreate, NewsletterSubscribe
from datetime import datetime
from pathlib import Path
import uuid
import os
import shutil

router = APIRouter(prefix="/api", tags=["Other"])

# MongoDB connection will be injected
db = None

# Upload directory setup
UPLOAD_DIR = Path(__file__).parent.parent / 'uploads'
UPLOAD_DIR.mkdir(exist_ok=True)

def set_db(database):
    global db
    db = database

@router.post("/contact")
async def submit_contact(contact: ContactCreate):
    """Submit a contact form"""
    contact_data = contact.dict()
    contact_data["id"] = str(uuid.uuid4())
    contact_data["created_at"] = datetime.utcnow()
    
    await db.contacts.insert_one(contact_data)
    
    return {"message": "Contact form submitted successfully"}

@router.post("/newsletter/subscribe")
async def subscribe_newsletter(subscriber: NewsletterSubscribe):
    """Subscribe to newsletter"""
    # Check if already subscribed
    existing = await db.newsletter_subscribers.find_one({"email": subscriber.email})
    if existing:
        return {"message": "Email already subscribed"}
    
    subscriber_data = subscriber.dict()
    subscriber_data["id"] = str(uuid.uuid4())
    subscriber_data["subscribed_at"] = datetime.utcnow()
    
    await db.newsletter_subscribers.insert_one(subscriber_data)
    
    return {"message": "Successfully subscribed to newsletter"}

@router.post("/upload/image")
async def upload_image(file: UploadFile = File(...)):
    """Upload an image file"""
    # Validate file type
    allowed_extensions = [".jpg", ".jpeg", ".png", ".webp"]
    file_ext = os.path.splitext(file.filename)[1].lower()
    
    if file_ext not in allowed_extensions:
        raise HTTPException(status_code=400, detail="Invalid file type. Allowed: jpg, jpeg, png, webp")
    
    # Generate unique filename
    unique_filename = f"{uuid.uuid4()}{file_ext}"
    file_path = UPLOAD_DIR / unique_filename
    
    # Save file
    with open(file_path, "wb") as buffer:
        shutil.copyfileobj(file.file, buffer)
    
    # Return URL
    file_url = f"/api/uploads/{unique_filename}"
    
    return {"url": file_url, "filename": unique_filename}

@router.get("/uploads/{filename}")
async def get_uploaded_image(filename: str):
    """Serve uploaded images"""
    file_path = UPLOAD_DIR / filename
    
    if not file_path.exists():
        raise HTTPException(status_code=404, detail="Image not found")
    
    return FileResponse(str(file_path))
