from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session
from ...shared.config.database import get_db
from ...security.middleware.auth import authorize_roles
from ...auth.models.user import User
from ..schemas.admin_privacy import CookieIntegrationSettings, CookieIntegrationSettingsResponse, CookiePolicySettings, CookiePolicySettingsResponse
from ...security.services.privacy_admin_service import privacy_admin_service
router = APIRouter(prefix='/admin/privacy', tags=['admin-privacy'])

@router.get('/cookie-policy', response_model=CookiePolicySettingsResponse, status_code=status.HTTP_200_OK)
def get_cookie_policy(db: Session=Depends(get_db), _: User=Depends(authorize_roles('admin'))) -> CookiePolicySettingsResponse:
    settings = privacy_admin_service.get_policy_settings(db)
    policy = privacy_admin_service.get_or_create_policy(db)
    updated_by_name = policy.updated_by.full_name if getattr(policy, 'updated_by', None) else None
    return CookiePolicySettingsResponse(data=settings, updated_at=policy.updated_at, updated_by=updated_by_name)

@router.put('/cookie-policy', response_model=CookiePolicySettingsResponse, status_code=status.HTTP_200_OK)
def update_cookie_policy(payload: CookiePolicySettings, db: Session=Depends(get_db), current_user: User=Depends(authorize_roles('admin'))) -> CookiePolicySettingsResponse:
    policy = privacy_admin_service.update_policy(db, payload, current_user)
    settings = privacy_admin_service.get_policy_settings(db)
    updated_by_name = policy.updated_by.full_name if getattr(policy, 'updated_by', None) else None
    return CookiePolicySettingsResponse(data=settings, updated_at=policy.updated_at, updated_by=updated_by_name)

@router.get('/integrations', response_model=CookieIntegrationSettingsResponse, status_code=status.HTTP_200_OK)
def get_cookie_integrations(db: Session=Depends(get_db), _: User=Depends(authorize_roles('admin'))) -> CookieIntegrationSettingsResponse:
    settings = privacy_admin_service.get_integration_settings(db)
    cfg = privacy_admin_service.get_or_create_integrations(db)
    updated_by_name = cfg.updated_by.full_name if getattr(cfg, 'updated_by', None) else None
    return CookieIntegrationSettingsResponse(data=settings, updated_at=cfg.updated_at, updated_by=updated_by_name)

@router.put('/integrations', response_model=CookieIntegrationSettingsResponse, status_code=status.HTTP_200_OK)
def update_cookie_integrations(payload: CookieIntegrationSettings, db: Session=Depends(get_db), current_user: User=Depends(authorize_roles('admin'))) -> CookieIntegrationSettingsResponse:
    cfg = privacy_admin_service.update_integrations(db, payload, current_user)
    settings = privacy_admin_service.get_integration_settings(db)
    updated_by_name = cfg.updated_by.full_name if getattr(cfg, 'updated_by', None) else None
    return CookieIntegrationSettingsResponse(data=settings, updated_at=cfg.updated_at, updated_by=updated_by_name)