#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
认证服务层
处理用户认证相关的业务逻辑
"""

from config import get_user_by_username

def authenticate_user(username, password):
    """验证用户登录"""
    try:
        user = get_user_by_username(username)
        if user and user['password'] == password:
            return {
                'success': True,
                'user': user,
                'message': '登录成功'
            }
        else:
            return {
                'success': False,
                'message': '用户名或密码错误'
            }
    except Exception as e:
        print(f"❌ 用户认证失败: {e}")
        return {
            'success': False,
            'message': f'认证失败: {str(e)}'
        }

def check_clinic_access(user, clinic_id):
    """检查用户是否有权限访问指定门诊"""
    try:
        # 管理员可以访问所有门诊
        if user.get('role') == 'admin':
            return True
        
        # 普通用户只能访问自己的门诊
        return user.get('clinic_id') == clinic_id
    except Exception as e:
        print(f"❌ 权限检查失败: {e}")
        return False

def get_user_clinics(user):
    """获取用户可访问的门诊列表"""
    try:
        if user.get('role') == 'admin':
            # 管理员可以访问所有门诊
            from config import CLINIC_CONFIG
            return list(CLINIC_CONFIG.keys())
        else:
            # 普通用户只能访问自己的门诊
            clinic_id = user.get('clinic_id')
            return [clinic_id] if clinic_id else []
    except Exception as e:
        print(f"❌ 获取用户门诊列表失败: {e}")
        return []
