from sqlalchemy.orm import Session
from ...content.models.cookie_policy import CookiePolicy
from ...content.models.cookie_integration_config import CookieIntegrationConfig
from ...auth.models.user import User
from ...content.schemas.admin_privacy import CookieIntegrationSettings, CookiePolicySettings, PublicPrivacyConfig

class PrivacyAdminService:

    @staticmethod
    def get_or_create_policy(db: Session) -> CookiePolicy:
        policy = db.query(CookiePolicy).first()
        if policy:
            return policy
        policy = CookiePolicy()
        db.add(policy)
        db.commit()
        db.refresh(policy)
        return policy

    @staticmethod
    def get_policy_settings(db: Session) -> CookiePolicySettings:
        policy = PrivacyAdminService.get_or_create_policy(db)
        return CookiePolicySettings(analytics_enabled=policy.analytics_enabled, marketing_enabled=policy.marketing_enabled, preferences_enabled=policy.preferences_enabled)

    @staticmethod
    def update_policy(db: Session, settings: CookiePolicySettings, updated_by: User | None) -> CookiePolicy:
        policy = PrivacyAdminService.get_or_create_policy(db)
        policy.analytics_enabled = settings.analytics_enabled
        policy.marketing_enabled = settings.marketing_enabled
        policy.preferences_enabled = settings.preferences_enabled
        if updated_by:
            policy.updated_by_id = updated_by.id
        db.add(policy)
        db.commit()
        db.refresh(policy)
        return policy

    @staticmethod
    def get_or_create_integrations(db: Session) -> CookieIntegrationConfig:
        config = db.query(CookieIntegrationConfig).first()
        if config:
            return config
        config = CookieIntegrationConfig()
        db.add(config)
        db.commit()
        db.refresh(config)
        return config

    @staticmethod
    def get_integration_settings(db: Session) -> CookieIntegrationSettings:
        cfg = PrivacyAdminService.get_or_create_integrations(db)
        return CookieIntegrationSettings(ga_measurement_id=cfg.ga_measurement_id, fb_pixel_id=cfg.fb_pixel_id)

    @staticmethod
    def update_integrations(db: Session, settings: CookieIntegrationSettings, updated_by: User | None) -> CookieIntegrationConfig:
        cfg = PrivacyAdminService.get_or_create_integrations(db)
        cfg.ga_measurement_id = settings.ga_measurement_id
        cfg.fb_pixel_id = settings.fb_pixel_id
        if updated_by:
            cfg.updated_by_id = updated_by.id
        db.add(cfg)
        db.commit()
        db.refresh(cfg)
        return cfg

    @staticmethod
    def get_public_privacy_config(db: Session) -> PublicPrivacyConfig:
        policy = PrivacyAdminService.get_policy_settings(db)
        integrations = PrivacyAdminService.get_integration_settings(db)
        return PublicPrivacyConfig(policy=policy, integrations=integrations)
privacy_admin_service = PrivacyAdminService()