"""
Middleware para agregar headers de no-cache a las respuestas
"""
from fastapi.responses import HTMLResponse
from fastapi.security import HTTPAuthorizationCredentials
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
from auth.security import get_current_user
from config import settings
import datetime
from logging import getLogger

logger = getLogger(__name__)

start_time = datetime.time(10, 0, 0)
end_time = datetime.time(23, 30, 0)

class EmptyUser:
  def __init__(self):
    self.permissions = 0

class InTimeMiddleware(BaseHTTPMiddleware):
    """
    Middleware que revisa si la peticion se hizo dentro del horario de funcionamiento del local
    10:00 a 23:30 horario de Chile
    """
    
    async def dispatch(self, request: Request, call_next):
        if "admin" in request.headers.get("Origin", ""):
            return await call_next(request)
        authorization = request.headers.get("Authorization")
        if not authorization:
          if settings.IS_OPEN_STORE:
            return await call_next(request)
          else:
            return HTMLResponse(""" 
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Local Cerrando :(</title>
  <script src="https://cdn.tailwindcss.com?plugins=forms,container-queries"></script>
</head>
<body>
      <!-- Header -->
    <div class="bg-[#101419] h-screen flex justify-center items-center flex- px-6 py-8 text-white text-center relative">

      <!-- Icono principal -->
      <div class="text-6xl mb-3">😫</div>

      <!-- Título -->
      <h2 class="text-2xl font-bold mb-2">¡El local se encuentra cerrado!</h2>
    </div>
</body>
</html>
                                """, status_code=420)
            
        time = datetime.datetime.now().time()
        try:
          user = await get_current_user(
                HTTPAuthorizationCredentials(scheme="Bearer", credentials=authorization)
            )
        except Exception as e:
          logger.warning(f"Not user verified in {request.url.path}: {e}")
          user = EmptyUser()
            
        if ((time >= start_time and time <= end_time) and settings.IS_OPEN_STORE) or (user.permissions or 0) >= 1:
            response = await call_next(request)
            return response
        else:
            return HTMLResponse(""" 
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Local Cerrando :(</title>
  <script src="https://cdn.tailwindcss.com?plugins=forms,container-queries"></script>
</head>
<body>
      <!-- Header -->
    <div class="bg-[#101419] h-screen flex justify-center items-center flex- px-6 py-8 text-white text-center relative">

      <!-- Icono principal -->
      <div class="text-6xl mb-3">😫</div>

      <!-- Título -->
      <h2 class="text-2xl font-bold mb-2">¡El local se encuentra cerrado!</h2>
    </div>
</body>
</html>
                                """, status_code=420)
