"""
API views for business/tenant management
"""
import base64
import uuid
from django.core.files.base import ContentFile
from django.db import connection
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response


# =============================================================================
# Sandbox Mode API
# =============================================================================

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def sandbox_status_view(request):
    """
    Get current sandbox mode status for the authenticated user.
    GET /api/sandbox/status/

    Returns:
        - sandbox_mode: Whether user is currently in sandbox mode
        - sandbox_enabled: Whether sandbox is available for this business
        - sandbox_schema: The name of the sandbox schema (if enabled)
    """
    user = request.user
    tenant = user.tenant

    if not tenant:
        return Response({
            'sandbox_mode': False,
            'sandbox_enabled': False,
            'sandbox_schema': None,
        })

    return Response({
        'sandbox_mode': request.session.get('sandbox_mode', False),
        'sandbox_enabled': tenant.sandbox_enabled,
        'sandbox_schema': tenant.sandbox_schema_name if tenant.sandbox_enabled else None,
    })


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def sandbox_toggle_view(request):
    """
    Toggle between live and sandbox mode.
    POST /api/sandbox/toggle/

    Request body:
        - sandbox: boolean - True to enable sandbox mode, False for live mode

    Returns:
        - sandbox_mode: The new sandbox mode state
        - message: Confirmation message
    """
    user = request.user
    tenant = user.tenant

    if not tenant:
        return Response(
            {'error': 'No business associated with user'},
            status=status.HTTP_403_FORBIDDEN
        )

    if not tenant.sandbox_enabled:
        return Response(
            {'error': 'Sandbox mode is not enabled for this business'},
            status=status.HTTP_403_FORBIDDEN
        )

    enable_sandbox = request.data.get('sandbox', False)

    # Validate that sandbox schema exists before enabling
    if enable_sandbox and not tenant.sandbox_schema_name:
        return Response(
            {'error': 'Sandbox schema not configured. Please contact support.'},
            status=status.HTTP_400_BAD_REQUEST
        )

    # Store sandbox mode in session
    request.session['sandbox_mode'] = bool(enable_sandbox)

    mode_name = 'Test' if enable_sandbox else 'Live'
    return Response({
        'sandbox_mode': enable_sandbox,
        'message': f'Switched to {mode_name} mode',
    })


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def sandbox_reset_view(request):
    """
    Reset sandbox data to initial state.
    POST /api/sandbox/reset/

    This clears all data in the sandbox schema. Use with caution!
    Only available to business owners.
    """
    user = request.user
    tenant = user.tenant

    if not tenant:
        return Response(
            {'error': 'No business associated with user'},
            status=status.HTTP_403_FORBIDDEN
        )

    # Only owners can reset sandbox
    allowed_roles = ['OWNER', 'TENANT_OWNER', 'SUPERUSER', 'PLATFORM_MANAGER']
    if user.role.upper() not in allowed_roles:
        return Response(
            {'error': 'Only business owners can reset sandbox data'},
            status=status.HTTP_403_FORBIDDEN
        )

    if not tenant.sandbox_enabled or not tenant.sandbox_schema_name:
        return Response(
            {'error': 'Sandbox mode is not available for this business'},
            status=status.HTTP_403_FORBIDDEN
        )

    # TODO: Implement actual reset logic
    # This would typically:
    # 1. Drop all tables in sandbox schema (keep migrations)
    # 2. Re-run migrations on sandbox schema
    # 3. Optionally seed with sample data

    return Response({
        'message': 'Sandbox data reset successfully',
        'sandbox_schema': tenant.sandbox_schema_name,
    })


@api_view(['GET'])
@permission_classes([IsAuthenticated])
def current_business_view(request):
    """
    Get current business (tenant) for the authenticated user
    GET /api/business/current/

    Returns null if user is a platform user without a tenant
    """
    user = request.user
    tenant = user.tenant

    # Platform users don't have a tenant
    if not tenant:
        return Response(None, status=status.HTTP_200_OK)

    # Get subdomain from primary domain
    subdomain = None
    primary_domain = tenant.domains.filter(is_primary=True).first()
    if primary_domain:
        # Extract subdomain from domain (e.g., "mybusiness.lvh.me" -> "mybusiness")
        domain_parts = primary_domain.domain.split('.')
        if len(domain_parts) > 0:
            subdomain = domain_parts[0]

    # Get plan permissions from billing system entitlements
    # Use the actual feature codes from the billing catalog
    permissions = {
        'sms_reminders': tenant.has_feature('sms_enabled'),
        'webhooks': tenant.has_feature('integrations_enabled'),
        'api_access': tenant.has_feature('api_access'),
        'custom_domain': tenant.has_feature('custom_domain'),
        'white_label': tenant.has_feature('white_label'),
        'custom_oauth': tenant.has_feature('can_manage_oauth'),
        'automations': tenant.has_feature('can_use_automations'),
        'can_create_automations': tenant.has_feature('can_create_automations'),
        'tasks': tenant.has_feature('can_use_tasks'),
        'export_data': tenant.has_feature('can_export_data'),
        'video_conferencing': tenant.has_feature('can_add_video_conferencing'),
        'two_factor_auth': tenant.has_feature('team_permissions'),
        'masked_calling': tenant.has_feature('masked_calling_enabled'),
        'pos_system': tenant.has_feature('can_use_pos'),
        'mobile_app': tenant.has_feature('mobile_app_access'),
        'contracts': tenant.has_feature('can_use_contracts'),
        'multi_location': tenant.has_feature('multi_location'),
    }

    # Get plan name from billing subscription
    plan_name = None
    if hasattr(tenant, 'billing_subscription') and tenant.billing_subscription:
        plan_name = tenant.billing_subscription.plan_version.plan.code

    business_data = {
        'id': tenant.id,
        'name': tenant.name,
        'subdomain': subdomain or tenant.schema_name,
        'plan': plan_name,
        'status': 'active' if tenant.is_active else 'inactive',
        'created_at': tenant.created_on.isoformat() if tenant.created_on else None,
        # Branding fields from Tenant model
        'primary_color': tenant.primary_color,
        'secondary_color': tenant.secondary_color,
        'logo_url': request.build_absolute_uri(tenant.logo.url) if tenant.logo else None,
        'email_logo_url': request.build_absolute_uri(tenant.email_logo.url) if tenant.email_logo else None,
        'logo_display_mode': tenant.logo_display_mode,
        # Timezone settings
        'timezone': tenant.timezone,
        'timezone_display_mode': tenant.timezone_display_mode,
        # Booking settings
        'booking_return_url': tenant.booking_return_url or '',
        # Booking page customization
        'service_selection_heading': tenant.service_selection_heading or 'Choose your experience',
        'service_selection_subheading': tenant.service_selection_subheading or 'Select a service to begin your booking.',
        # Other optional fields with defaults
        'whitelabel_enabled': False,
        'resources_can_reschedule': False,
        'require_payment_method_to_book': False,
        'cancellation_window_hours': 24,
        'late_cancellation_fee_percent': 0,
        'initial_setup_complete': False,
        'website_pages': {},
        'customer_dashboard_content': [],
        # Platform permissions
        'can_manage_oauth_credentials': tenant.has_feature('can_manage_oauth'),
        'payments_enabled': tenant.payment_mode != 'none',
        # Plan permissions (what features are available based on subscription)
        'plan_permissions': permissions,
    }

    return Response(business_data, status=status.HTTP_200_OK)


@api_view(['PATCH'])
@permission_classes([IsAuthenticated])
def update_business_view(request):
    """
    Update business (tenant) settings for the authenticated user
    PATCH /api/business/current/update/

    Only business owners can update settings
    """
    user = request.user
    tenant = user.tenant

    # Platform users don't have a tenant
    if not tenant:
        return Response({'error': 'No business found'}, status=status.HTTP_404_NOT_FOUND)

    # Only owners can update business settings
    allowed_roles = ['OWNER', 'TENANT_OWNER', 'SUPERUSER', 'PLATFORM_MANAGER']
    if user.role.upper() not in allowed_roles:
        return Response({'error': f'Only business owners can update settings. Your role: {user.role}'}, status=status.HTTP_403_FORBIDDEN)

    # Update fields if provided in request
    if 'name' in request.data:
        tenant.name = request.data['name']

    if 'primary_color' in request.data:
        tenant.primary_color = request.data['primary_color']

    if 'secondary_color' in request.data:
        tenant.secondary_color = request.data['secondary_color']

    if 'logo_display_mode' in request.data:
        tenant.logo_display_mode = request.data['logo_display_mode']

    if 'timezone' in request.data:
        tenant.timezone = request.data['timezone']

    if 'timezone_display_mode' in request.data:
        tenant.timezone_display_mode = request.data['timezone_display_mode']

    if 'booking_return_url' in request.data:
        tenant.booking_return_url = request.data['booking_return_url'] or ''

    if 'service_selection_heading' in request.data:
        tenant.service_selection_heading = request.data['service_selection_heading'] or 'Choose your experience'

    if 'service_selection_subheading' in request.data:
        tenant.service_selection_subheading = request.data['service_selection_subheading'] or 'Select a service to begin your booking.'

    # Handle logo uploads (base64 data URLs)
    if 'logo_url' in request.data:
        logo_data = request.data['logo_url']
        if logo_data and logo_data.startswith('data:image'):
            # Extract base64 data and file extension
            format_str, imgstr = logo_data.split(';base64,')
            ext = format_str.split('/')[-1]
            # Decode base64 and create Django file
            data = ContentFile(base64.b64decode(imgstr), name=f'logo_{uuid.uuid4()}.{ext}')
            # Delete old logo if exists
            if tenant.logo:
                tenant.logo.delete(save=False)
            tenant.logo = data
        elif logo_data is None or logo_data == '':
            # Remove logo if set to None or empty string
            if tenant.logo:
                tenant.logo.delete(save=False)
            tenant.logo = None

    if 'email_logo_url' in request.data:
        email_logo_data = request.data['email_logo_url']
        if email_logo_data and email_logo_data.startswith('data:image'):
            # Extract base64 data and file extension
            format_str, imgstr = email_logo_data.split(';base64,')
            ext = format_str.split('/')[-1]
            # Decode base64 and create Django file
            data = ContentFile(base64.b64decode(imgstr), name=f'email_logo_{uuid.uuid4()}.{ext}')
            # Delete old email logo if exists
            if tenant.email_logo:
                tenant.email_logo.delete(save=False)
            tenant.email_logo = data
        elif email_logo_data is None or email_logo_data == '':
            # Remove email logo if set to None or empty string
            if tenant.email_logo:
                tenant.email_logo.delete(save=False)
            tenant.email_logo = None

    # Save the tenant
    tenant.save()

    # Return updated business data
    subdomain = None
    primary_domain = tenant.domains.filter(is_primary=True).first()
    if primary_domain:
        domain_parts = primary_domain.domain.split('.')
        if len(domain_parts) > 0:
            subdomain = domain_parts[0]

    # Get plan name from billing subscription
    plan_name = None
    if hasattr(tenant, 'billing_subscription') and tenant.billing_subscription:
        plan_name = tenant.billing_subscription.plan_version.plan.code

    business_data = {
        'id': tenant.id,
        'name': tenant.name,
        'subdomain': subdomain or tenant.schema_name,
        'plan': plan_name,
        'status': 'active' if tenant.is_active else 'inactive',
        'created_at': tenant.created_on.isoformat() if tenant.created_on else None,
        'primary_color': tenant.primary_color,
        'secondary_color': tenant.secondary_color,
        'logo_url': request.build_absolute_uri(tenant.logo.url) if tenant.logo else None,
        'email_logo_url': request.build_absolute_uri(tenant.email_logo.url) if tenant.email_logo else None,
        'logo_display_mode': tenant.logo_display_mode,
        'timezone': tenant.timezone,
        'timezone_display_mode': tenant.timezone_display_mode,
        'whitelabel_enabled': False,
        'resources_can_reschedule': False,
        'require_payment_method_to_book': False,
        'cancellation_window_hours': 24,
        'late_cancellation_fee_percent': 0,
        'initial_setup_complete': False,
        'website_pages': {},
        'customer_dashboard_content': [],
    }

    return Response(business_data)


# Available OAuth providers that the platform supports
AVAILABLE_OAUTH_PROVIDERS = [
    {
        'id': 'google',
        'name': 'Google',
        'icon': 'google',
        'description': 'Sign in with Google accounts',
    },
    {
        'id': 'facebook',
        'name': 'Facebook',
        'icon': 'facebook',
        'description': 'Sign in with Facebook accounts',
    },
    {
        'id': 'apple',
        'name': 'Apple',
        'icon': 'apple',
        'description': 'Sign in with Apple ID',
    },
]


@api_view(['GET', 'PATCH'])
@permission_classes([IsAuthenticated])
def oauth_settings_view(request):
    """
    Get or update OAuth settings for the current business
    GET /api/business/oauth-settings/
    PATCH /api/business/oauth-settings/
    """
    user = request.user
    tenant = user.tenant

    # Platform users don't have a tenant
    if not tenant:
        return Response({'error': 'No business found'}, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        return Response({
            'settings': {
                'enabled_providers': tenant.oauth_enabled_providers or [],
                'allow_registration': tenant.oauth_allow_registration,
                'auto_link_by_email': tenant.oauth_auto_link_by_email,
                'use_custom_credentials': tenant.oauth_use_custom_credentials,
            },
            'available_providers': AVAILABLE_OAUTH_PROVIDERS,
        }, status=status.HTTP_200_OK)

    # PATCH - update settings
    # Only owners can update OAuth settings
    if user.role.lower() != 'tenant_owner':
        return Response({'error': 'Only business owners can update OAuth settings'}, status=status.HTTP_403_FORBIDDEN)

    data = request.data

    if 'enabled_providers' in data:
        # Validate that all providers are valid
        valid_provider_ids = [p['id'] for p in AVAILABLE_OAUTH_PROVIDERS]
        enabled = data['enabled_providers']
        if not isinstance(enabled, list):
            return Response({'error': 'enabled_providers must be a list'}, status=status.HTTP_400_BAD_REQUEST)
        for provider in enabled:
            if provider not in valid_provider_ids:
                return Response({'error': f'Invalid provider: {provider}'}, status=status.HTTP_400_BAD_REQUEST)
        tenant.oauth_enabled_providers = enabled

    if 'allow_registration' in data:
        tenant.oauth_allow_registration = bool(data['allow_registration'])

    if 'auto_link_by_email' in data:
        tenant.oauth_auto_link_by_email = bool(data['auto_link_by_email'])

    if 'use_custom_credentials' in data:
        tenant.oauth_use_custom_credentials = bool(data['use_custom_credentials'])

    tenant.save()

    return Response({
        'settings': {
            'enabled_providers': tenant.oauth_enabled_providers or [],
            'allow_registration': tenant.oauth_allow_registration,
            'auto_link_by_email': tenant.oauth_auto_link_by_email,
            'use_custom_credentials': tenant.oauth_use_custom_credentials,
        },
        'available_providers': AVAILABLE_OAUTH_PROVIDERS,
    }, status=status.HTTP_200_OK)


@api_view(['GET', 'POST'])
@permission_classes([IsAuthenticated])
def custom_domains_view(request):
    """
    List or create custom domains for the current business
    GET /api/business/domains/
    POST /api/business/domains/
    """
    user = request.user
    tenant = user.tenant

    # Platform users don't have a tenant
    if not tenant:
        return Response({'error': 'No business found'}, status=status.HTTP_404_NOT_FOUND)

    # Only owners can manage domains
    if user.role.lower() != 'tenant_owner':
        return Response({'error': 'Only business owners can manage domains'}, status=status.HTTP_403_FORBIDDEN)

    from smoothschedule.identity.core.models import Domain

    if request.method == 'GET':
        # List all domains for this tenant
        domains = Domain.objects.filter(tenant=tenant)
        domain_list = []
        for d in domains:
            domain_list.append({
                'id': d.id,
                'domain': d.domain,
                'is_primary': d.is_primary,
                'is_verified': bool(d.verified_at),
                'ssl_provisioned': bool(d.ssl_certificate_arn),
                'verification_token': '',  # Not used yet
                'dns_txt_record': f'_smoothschedule-verify.{d.domain}',
                'dns_txt_record_name': f'_smoothschedule-verify',
                'created_at': d.verified_at.isoformat() if d.verified_at else None,
                'verified_at': d.verified_at.isoformat() if d.verified_at else None,
            })
        return Response(domain_list, status=status.HTTP_200_OK)

    # POST - create a new custom domain
    domain_name = request.data.get('domain', '').lower().strip()
    if not domain_name:
        return Response({'error': 'Domain name is required'}, status=status.HTTP_400_BAD_REQUEST)

    # Basic domain validation
    import re
    if not re.match(r'^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$', domain_name):
        return Response({'error': 'Invalid domain format'}, status=status.HTTP_400_BAD_REQUEST)

    # Check if domain already exists
    if Domain.objects.filter(domain=domain_name).exists():
        return Response({'error': 'Domain already in use'}, status=status.HTTP_409_CONFLICT)

    # Create the custom domain
    new_domain = Domain.objects.create(
        tenant=tenant,
        domain=domain_name,
        is_primary=False,
        is_custom_domain=True,
    )

    return Response({
        'id': new_domain.id,
        'domain': new_domain.domain,
        'is_primary': new_domain.is_primary,
        'is_verified': False,
        'ssl_provisioned': False,
        'verification_token': '',
        'dns_txt_record': f'_smoothschedule-verify.{new_domain.domain}',
        'dns_txt_record_name': '_smoothschedule-verify',
        'created_at': None,
        'verified_at': None,
    }, status=status.HTTP_201_CREATED)


@api_view(['GET', 'DELETE'])
@permission_classes([IsAuthenticated])
def custom_domain_detail_view(request, domain_id):
    """
    Get or delete a specific custom domain
    GET /api/business/domains/<domain_id>/
    DELETE /api/business/domains/<domain_id>/
    """
    user = request.user
    tenant = user.tenant

    # Platform users don't have a tenant
    if not tenant:
        return Response({'error': 'No business found'}, status=status.HTTP_404_NOT_FOUND)

    # Only owners can manage domains
    if user.role.lower() != 'tenant_owner':
        return Response({'error': 'Only business owners can manage domains'}, status=status.HTTP_403_FORBIDDEN)

    from smoothschedule.identity.core.models import Domain

    try:
        domain = Domain.objects.get(id=domain_id, tenant=tenant)
    except Domain.DoesNotExist:
        return Response({'error': 'Domain not found'}, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        return Response({
            'id': domain.id,
            'domain': domain.domain,
            'is_primary': domain.is_primary,
            'is_verified': bool(domain.verified_at),
            'ssl_provisioned': bool(domain.ssl_certificate_arn),
            'verification_token': '',
            'dns_txt_record': f'_smoothschedule-verify.{domain.domain}',
            'dns_txt_record_name': '_smoothschedule-verify',
            'created_at': domain.verified_at.isoformat() if domain.verified_at else None,
            'verified_at': domain.verified_at.isoformat() if domain.verified_at else None,
        }, status=status.HTTP_200_OK)

    # DELETE - remove the domain
    if domain.is_primary:
        return Response({'error': 'Cannot delete primary domain'}, status=status.HTTP_400_BAD_REQUEST)

    domain.delete()
    return Response(status=status.HTTP_204_NO_CONTENT)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def custom_domain_verify_view(request, domain_id):
    """
    Verify a custom domain by checking DNS
    POST /api/business/domains/<domain_id>/verify/
    """
    user = request.user
    tenant = user.tenant

    if not tenant:
        return Response({'error': 'No business found'}, status=status.HTTP_404_NOT_FOUND)

    if user.role.lower() != 'tenant_owner':
        return Response({'error': 'Only business owners can manage domains'}, status=status.HTTP_403_FORBIDDEN)

    from smoothschedule.identity.core.models import Domain
    from django.utils import timezone
    import socket

    try:
        domain = Domain.objects.get(id=domain_id, tenant=tenant)
    except Domain.DoesNotExist:
        return Response({'error': 'Domain not found'}, status=status.HTTP_404_NOT_FOUND)

    # Try to resolve the domain
    try:
        # Check if the domain resolves to our server
        # In production, this would check if DNS points to our infrastructure
        socket.gethostbyname(domain.domain)
        domain.verified_at = timezone.now()
        domain.save()
        return Response({
            'verified': True,
            'message': 'Domain verified successfully',
        }, status=status.HTTP_200_OK)
    except socket.gaierror:
        return Response({
            'verified': False,
            'message': 'Domain DNS not configured. Please add a CNAME record pointing to your subdomain.',
        }, status=status.HTTP_200_OK)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def custom_domain_set_primary_view(request, domain_id):
    """
    Set a custom domain as the primary domain
    POST /api/business/domains/<domain_id>/set-primary/
    """
    user = request.user
    tenant = user.tenant

    if not tenant:
        return Response({'error': 'No business found'}, status=status.HTTP_404_NOT_FOUND)

    if user.role.lower() != 'tenant_owner':
        return Response({'error': 'Only business owners can manage domains'}, status=status.HTTP_403_FORBIDDEN)

    from smoothschedule.identity.core.models import Domain

    try:
        domain = Domain.objects.get(id=domain_id, tenant=tenant)
    except Domain.DoesNotExist:
        return Response({'error': 'Domain not found'}, status=status.HTTP_404_NOT_FOUND)

    # Domain must be verified to be set as primary
    if not domain.verified_at:
        return Response({'error': 'Domain must be verified before setting as primary'}, status=status.HTTP_400_BAD_REQUEST)

    # Unset current primary domain
    Domain.objects.filter(tenant=tenant, is_primary=True).update(is_primary=False)

    # Set this domain as primary
    domain.is_primary = True
    domain.save()

    return Response({
        'id': domain.id,
        'domain': domain.domain,
        'is_primary': domain.is_primary,
        'is_verified': bool(domain.verified_at),
        'ssl_provisioned': bool(domain.ssl_certificate_arn),
        'verification_token': '',
        'dns_txt_record': f'_smoothschedule-verify.{domain.domain}',
        'dns_txt_record_name': '_smoothschedule-verify',
        'created_at': domain.verified_at.isoformat() if domain.verified_at else None,
        'verified_at': domain.verified_at.isoformat() if domain.verified_at else None,
    }, status=status.HTTP_200_OK)


@api_view(['GET', 'PATCH'])
@permission_classes([IsAuthenticated])
def oauth_credentials_view(request):
    """
    Get or update custom OAuth credentials for the current business
    GET /api/business/oauth-credentials/
    PATCH /api/business/oauth-credentials/

    Credentials are stored per-provider:
    {
        "google": {"client_id": "...", "client_secret": "..."},
        "facebook": {"client_id": "...", "client_secret": "..."},
        ...
    }
    """
    user = request.user
    tenant = user.tenant

    # Platform users don't have a tenant
    if not tenant:
        return Response({'error': 'No business found'}, status=status.HTTP_404_NOT_FOUND)

    # Only owners can view/update credentials
    if user.role.lower() != 'tenant_owner':
        return Response({'error': 'Only business owners can manage OAuth credentials'}, status=status.HTTP_403_FORBIDDEN)

    if request.method == 'GET':
        # Return credentials with secrets masked
        credentials = tenant.oauth_credentials or {}
        masked_credentials = {}
        for provider, creds in credentials.items():
            masked_credentials[provider] = {
                'client_id': creds.get('client_id', ''),
                # Mask the secret - show first 4 chars if set
                'client_secret': ('****' + creds.get('client_secret', '')[-4:]) if creds.get('client_secret') else '',
                'has_secret': bool(creds.get('client_secret')),
            }
        return Response({
            'credentials': masked_credentials,
            'use_custom_credentials': tenant.oauth_use_custom_credentials,
        }, status=status.HTTP_200_OK)

    # PATCH - update credentials
    data = request.data
    valid_provider_ids = [p['id'] for p in AVAILABLE_OAUTH_PROVIDERS]

    if 'credentials' in data:
        credentials = data['credentials']
        if not isinstance(credentials, dict):
            return Response({'error': 'credentials must be an object'}, status=status.HTTP_400_BAD_REQUEST)

        # Merge with existing credentials (don't overwrite secrets if not provided)
        existing_credentials = tenant.oauth_credentials or {}
        for provider, creds in credentials.items():
            if provider not in valid_provider_ids:
                return Response({'error': f'Invalid provider: {provider}'}, status=status.HTTP_400_BAD_REQUEST)

            if provider not in existing_credentials:
                existing_credentials[provider] = {}

            if 'client_id' in creds:
                existing_credentials[provider]['client_id'] = creds['client_id']

            # Only update secret if provided and not masked value
            if 'client_secret' in creds and creds['client_secret'] and not creds['client_secret'].startswith('****'):
                existing_credentials[provider]['client_secret'] = creds['client_secret']

        tenant.oauth_credentials = existing_credentials

    if 'use_custom_credentials' in data:
        tenant.oauth_use_custom_credentials = bool(data['use_custom_credentials'])

    tenant.save()

    # Return masked credentials
    credentials = tenant.oauth_credentials or {}
    masked_credentials = {}
    for provider, creds in credentials.items():
        masked_credentials[provider] = {
            'client_id': creds.get('client_id', ''),
            'client_secret': ('****' + creds.get('client_secret', '')[-4:]) if creds.get('client_secret') else '',
            'has_secret': bool(creds.get('client_secret')),
        }

    return Response({
        'credentials': masked_credentials,
        'use_custom_credentials': tenant.oauth_use_custom_credentials,
    }, status=status.HTTP_200_OK)
