# System Architecture

## Architecture Decision

The recommended first implementation is a modular monolith with event-driven boundaries. This gives the team fast MVP delivery, strong transactional consistency for pharmacy workflows, and a clean migration path to microservices when modules such as POS, insurance claims, forecasting, and notifications need independent scaling.

## High-Level Diagram

```mermaid
flowchart TB
  subgraph Clients["Client Channels"]
    AdminWeb["Central Admin Dashboard\nNext.js RTL/EN"]
    PharmacyWeb["Daily Pharmacy Workflow\nNext.js"]
    POS["Fast POS Terminal\nWeb/PWA"]
    PatientApp["Patient Mobile App\nReact Native"]
    DoctorPortal["Doctor Portal/API"]
  end

  subgraph Edge["Edge and Security"]
    WAF["WAF + DDoS Protection"]
    Gateway["API Gateway\nOAuth2/JWT/Rate Limits"]
    IAM["Identity Provider\n2FA / SSO / RBAC"]
  end

  subgraph Core["Smart Pharmacy Hub Core"]
    Auth["Auth and Tenant Service"]
    Inventory["Inventory Hub"]
    Prescription["e-Prescription Service"]
    CDS["Clinical Decision Support"]
    POSBilling["POS and Billing"]
    Patients["Patient Management"]
    Reports["Compliance and Reports"]
    Integrations["Integration Hub"]
    AI["AI/ML Services\nForecasting/Fraud/Chatbot"]
  end

  subgraph Data["Data Platform"]
    Postgres["PostgreSQL\nTenant-Isolated OLTP"]
    Redis["Redis\nCache/Sessions/Queues"]
    Search["Elasticsearch/OpenSearch\nDrug + Patient Search"]
    ObjectStore["Encrypted Object Storage\nRx Images/Documents"]
    Warehouse["Analytics Warehouse\nBI/Metabase/Power BI"]
  end

  subgraph Eventing["Event-Driven Backbone"]
    Broker["Kafka/RabbitMQ"]
    Outbox["Transactional Outbox"]
  end

  subgraph External["External Systems"]
    HIS["HIS/EMR"]
    Insurance["Insurance APIs"]
    Suppliers["Supplier ERP/APIs"]
    Robotics["Robotic Dispensing"]
    IoT["Cold Chain IoT Sensors"]
    Payments["Mada/Apple Pay/Tabby/Tamara"]
    Notify["WhatsApp/SMS/Push"]
    Accounting["Odoo/SAP/QuickBooks"]
    MOH["MOH/ZATCA Reports"]
  end

  Clients --> WAF --> Gateway --> Core
  Gateway --> IAM
  Core --> Postgres
  Core --> Redis
  Core --> Search
  Core --> ObjectStore
  Core --> Outbox --> Broker
  Broker --> AI
  Broker --> Warehouse
  Integrations --> External
  Reports --> MOH
  AI --> Core
```

## Deployment Model

- Cloud-first: AWS EKS or Azure AKS, multi-AZ, multi-region read replicas for analytics and disaster recovery.
- On-premise profile: Kubernetes or Docker Compose with local PostgreSQL, Redis, and OpenSearch.
- Tenant isolation: shared database with strict `tenant_id` row-level security for MVP; optional dedicated schema/database for enterprise tenants.
- Data residency: deploy regional clusters for Saudi Arabia, UAE, and Egypt as required.

## Security and Compliance

- JWT access tokens with short TTL and refresh token rotation.
- OAuth2/OIDC federation for hospital and enterprise SSO.
- 2FA for privileged roles and pharmacists approving controlled workflows.
- Encryption at rest for PostgreSQL, Redis persistence, object storage, backups.
- Field-level encryption for high-risk PHI where required.
- Immutable audit trail for prescription, dispensing, billing, inventory, and user access events.
- Consent and data retention policies aligned with HIPAA, GDPR, and local MOH requirements.

## Core Event Topics

- `inventory.stock-lot.created`
- `inventory.stock-level.low`
- `inventory.stock-lot.near-expiry`
- `prescription.received`
- `prescription.clinical-warning.created`
- `dispensing.completed`
- `billing.invoice.created`
- `patient.medication-reminder.due`
- `iot.temperature.violation`
- `audit.event.recorded`
