from fastapi import APIRouter, HTTPException
from fastapi.responses import RedirectResponse

from ..db import database
from ..exceptions import ShortcodeNotFound, ShortcodeConflict
from ..utils import encoder
from ..schemas import UrlPayload
from ..services import UrlService

router = APIRouter()
url_service = UrlService(db=database)

@router.get("/{shortcode}")
async def redirect_to_original_url(shortcode: str):
    if not encoder.is_valid(shortcode):
        raise HTTPException(status_code=400, detail=f"Shortcode '{shortcode}' is not valid")

    try:
        url = await url_service.get_url_by_shortcode(shortcode)
        return RedirectResponse(url=url, status_code=302)
    except ShortcodeNotFound as e:
        raise HTTPException(status_code=404, detail=str(e)) from e


@router.post("/api/shorten")
async def create_url_shortcode(url_payload: UrlPayload):
    url = str(url_payload.url)

    try:
        return await url_service.generate_shortcode_and_save(url)
    except ShortcodeConflict as e:
        raise HTTPException(status_code=409, detail=str(e)) from e
    except:
        raise HTTPException(status_code=500, detail="Internal Server Error") from None
