# mlink-backend/src/config/security.py
import os
from flask_cors import CORS
from flask import Flask
from src.config.env_loader import env

class SecurityConfig:
    """보안 설정 클래스"""
    
    @staticmethod
    def configure_cors(app: Flask):
        """CORS 설정"""
        # 프로덕션 환경에서 허용할 도메인들
        allowed_origins = env.get_list('ALLOWED_ORIGINS', default=[
            'https://mlink.sellmall.co.kr',
            'https://www.sellmall.co.kr'
        ])
        
        # 개발 환경에서는 localhost도 허용
        if env.get('ENVIRONMENT') == 'development':
            allowed_origins.extend([
                'http://localhost:3000',
                'http://localhost:3001',
                'http://127.0.0.1:3000',
                'http://127.0.0.1:3001'
            ])
        
        CORS(
            app,
            origins=allowed_origins,
            methods=env.get_list('ALLOWED_METHODS', default=[
                'GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'
            ]),
            allow_headers=env.get_list('ALLOWED_HEADERS', default=[
                'Content-Type',
                'Authorization',
                'X-Requested-With',
                'X-CSRF-Token'
            ]),
            supports_credentials=True,
            max_age=3600  # 1시간
        )
    
    @staticmethod
    def configure_security_headers(app: Flask):
        """보안 헤더 설정"""
        @app.after_request
        def add_security_headers(response):
            # XSS 보호
            response.headers['X-Content-Type-Options'] = 'nosniff'
            response.headers['X-Frame-Options'] = 'DENY'
            response.headers['X-XSS-Protection'] = '1; mode=block'
            
            # HSTS (HTTPS 강제)
            response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
            
            # Content Security Policy
            csp = (
                "default-src 'self'; "
                "script-src 'self' 'unsafe-inline' 'unsafe-eval'; "
                "style-src 'self' 'unsafe-inline'; "
                "img-src 'self' data: https:; "
                "connect-src 'self' https://api.openai.com https://media.tenor.com; "
                "frame-ancestors 'none';"
            )
            response.headers['Content-Security-Policy'] = csp
            
            # Referrer Policy
            response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
            
            # Permissions Policy
            response.headers['Permissions-Policy'] = (
                'geolocation=(), '
                'microphone=(), '
                'camera=(), '
                'payment=(), '
                'usb=(), '
                'magnetometer=(), '
                'gyroscope=(), '
                'accelerometer=()'
            )
            
            return response