File size: 21,021 Bytes
f78b36a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c35b446
 
 
 
 
a133601
 
c35b446
 
 
 
 
 
 
 
 
 
 
 
 
395abdc
 
 
 
 
 
c35b446
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131aa2a
 
 
 
 
 
 
 
 
c35b446
 
 
 
131aa2a
a133601
c35b446
 
 
131aa2a
 
 
 
 
c35b446
a133601
c35b446
395abdc
 
 
 
 
 
 
c35b446
 
 
 
 
 
 
 
 
 
 
395abdc
 
 
 
 
 
 
 
 
 
 
 
 
 
c35b446
 
 
 
 
 
 
5f952c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c35b446
 
 
 
395abdc
 
 
 
 
 
 
 
 
 
c35b446
395abdc
 
 
 
 
 
b5a54b6
395abdc
 
 
c35b446
395abdc
 
 
 
 
 
c35b446
5f952c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27e706d
5f952c4
 
27e706d
 
 
c35b446
 
 
 
395abdc
c35b446
 
 
 
 
 
 
395abdc
 
 
 
 
 
 
 
 
 
 
 
c35b446
 
 
 
 
 
 
 
 
 
395abdc
 
 
 
 
 
 
 
c35b446
395abdc
c35b446
395abdc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c35b446
 
395abdc
 
c35b446
 
 
131aa2a
 
 
 
 
 
 
 
 
f78b36a
 
 
 
 
 
 
 
 
 
 
 
 
395abdc
 
 
131aa2a
395abdc
131aa2a
395abdc
 
131aa2a
 
 
 
395abdc
 
 
f78b36a
 
395abdc
f78b36a
 
 
 
 
 
 
 
 
 
683d259
 
 
 
 
 
c35b446
 
 
 
 
 
 
 
 
f78b36a
 
c35b446
f78b36a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
395abdc
 
 
 
 
 
 
 
 
 
f78b36a
 
 
 
395abdc
f78b36a
 
 
 
 
 
395abdc
 
 
f78b36a
 
395abdc
f78b36a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
395abdc
 
 
 
 
 
f78b36a
 
395abdc
f78b36a
 
 
 
 
 
 
 
 
 
80b0cdb
f78b36a
 
 
 
395abdc
 
 
 
 
 
 
 
 
 
 
 
 
f78b36a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
395abdc
 
80b0cdb
 
 
395abdc
f78b36a
 
395abdc
f78b36a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f963af3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f78b36a
 
 
 
 
 
 
 
 
395abdc
f78b36a
 
395abdc
f963af3
f78b36a
 
395abdc
 
f963af3
395abdc
f78b36a
 
 
 
 
683d259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
395abdc
 
683d259
395abdc
683d259
 
395abdc
683d259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
395abdc
 
 
 
 
 
 
 
683d259
 
 
 
 
395abdc
 
 
 
 
683d259
 
395abdc
683d259
 
 
 
 
 
c35b446
 
 
 
 
 
 
 
 
 
 
 
 
395abdc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c35b446
395abdc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c35b446
 
 
 
 
 
 
395abdc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27e706d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
/**
 * Prisma Schema for Maternal Health Support Backend
 * ORM CHOICE: Prisma
 * JUSTIFICATION:
 * - Type-safe database client with excellent TypeScript support
 * - Intuitive schema definition language
 * - Automatic migration generation
 * - Built-in connection pooling
 * - Great developer experience with Prisma Studio
 * - Strong PostgreSQL support
 * CLINICAL SAFETY PRINCIPLES:
 * - Data minimization enforced at schema level
 * - No free-text medical fields
 * - Enums for controlled vocabularies
 * - Timestamps for audit trails
 * - Strict validation rules
 */

generator client {
  provider   = "prisma-client-js"
  engineType = "library"
}

datasource db {
  provider = "postgresql"
}

/**
 * User Role Enum
 */
enum UserRole {
  SUPER_ADMIN
  FACILITY_ADMIN
  FACILITY_STAFF
  PATIENT
}

/**
 * Health Worker Type Enum
 */
enum HealthWorkerType {
  DOCTOR
  NURSE
  MIDWIFE
  COMMUNITY_HEALTH_WORKER
}

enum PatientRiskLevel {
  NORMAL
  HIGH
  CRITICAL
}

/**
 * Organization Entity
 */
model Organization {
  id          String   @id @default(uuid())
  name        String
  description String?
  isActive    Boolean  @default(true)
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt

  facilities Facility[]

  @@index([isActive])
  @@map("organization")
}

/**
 * Facility Status Enum
 */
enum FacilityStatus {
  PENDING
  ACTIVE
  SUSPENDED
}

/**
 * Facility Entity
 */
model Facility {
  id             String         @id @default(uuid())
  organizationId String?
  name           String
  address        String?
  phone          String?
  facilityCode   String         @unique
  isActive       Boolean        @default(true)
  status         FacilityStatus @default(ACTIVE)
  createdAt      DateTime       @default(now())
  updatedAt      DateTime       @updatedAt

  organization      Organization?       @relation(fields: [organizationId], references: [id], onDelete: Cascade)
  healthcareWorkers HealthcareWorker[]
  patients          Patient[]
  appointments      Appointment[]
  alerts            Alert[]
  referrals         Referral[]
  ancVisits         ANCVisit[]
  outgoingReferrals Referral[]         @relation("OutgoingReferrals")
  incomingReferrals Referral[]         @relation("IncomingReferrals")

  @@index([organizationId])
  @@index([facilityCode])
  @@index([isActive])
  @@map("facility")
}

/**
 * Healthcare Worker Entity
 */
model HealthcareWorker {
  id          String           @id @default(uuid())
  userId      String           @unique
  facilityId  String
  type        HealthWorkerType
  firstName   String
  lastName    String
  isSuspended Boolean          @default(false)
  createdAt   DateTime         @default(now())
  updatedAt   DateTime         @updatedAt

  userAuth UserAuth @relation(fields: [userId], references: [id], onDelete: Cascade)
  facility Facility @relation(fields: [facilityId], references: [id], onDelete: Cascade)

  ancVisits ANCVisit[]

  @@index([userId])
  @@index([facilityId])
  @@index([isSuspended])
  @@map("healthcare_worker")
}

/**
 * Blood Group Enum
 */
enum BloodGroup {
  A_POSITIVE
  A_NEGATIVE
  B_POSITIVE
  B_NEGATIVE
  O_POSITIVE
  O_NEGATIVE
  AB_POSITIVE
  AB_NEGATIVE
}

/**
 * Genotype Enum
 */
enum Genotype {
  AA
  AS
  AC
  SS
  SC
  CC
}

/**
 * Smoking Status Enum
 */
enum SmokingStatus {
  NEVER
  CURRENT
  FORMER
}

/**
 * Alcohol Use Enum
 */
enum AlcoholUse {
  NEVER
  OCCASIONAL
  REGULAR
}

/**
 * Substance Use Enum
 */
enum SubstanceUse {
  NEVER
  CURRENT
  FORMER
}

/**
 * Education Level Enum
 */
enum EducationLevel {
  NONE
  PRIMARY
  SECONDARY
  TERTIARY
}

/**
 * Booking Status Enum
 */
enum BookingStatus {
  BOOKED
  UNBOOKED
}

/**
 * Patient Entity
 */
model Patient {
  id                    String    @id @default(uuid())
  userId                String    @unique
  facilityId            String
  patientId             String    @unique
  firstName             String
  lastName              String
  phone                 String
  age                   Int
  address               String?
  gestationalAge        Int
  estimatedDeliveryDate DateTime?
  qrCode                String?
  isActive              Boolean   @default(true)
  createdAt             DateTime  @default(now())
  updatedAt             DateTime  @updatedAt

  userAuth     UserAuth      @relation(fields: [userId], references: [id], onDelete: Cascade)
  facility     Facility?      @relation(fields: [facilityId], references: [id], onDelete: Cascade)
  appointments Appointment[]
  alerts       Alert[]
  referrals    Referral[]

  ancVisits       ANCVisit[]
  status          PatientStatus    @default(ACTIVE)
  riskLevel       PatientRiskLevel @default(NORMAL)
  riskReason      String?
  latestRiskLevel RiskLevel        @default(LOW)
  lastVisitDate   DateTime?

  // --- Patient Information ---
  bloodGroup              BloodGroup?
  genotype                Genotype?
  emergencyContactName    String?
  emergencyContactPhone   String?
  emergencyContactRelation String?

  // --- Obstetric History ---
  gravidity               Int?       // G
  parity                  Int?       // P
  livingChildren          Int?
  previousMiscarriages    Int?
  previousAbortions       Int?
  previousStillbirths     Int?
  previousNeonatalDeaths  Int?
  previousCaesareans      Int?
  previousMultiplePregnancy Boolean?

  // --- Current Pregnancy ---
  lastMenstrualPeriod     DateTime?
  bookingStatus           BookingStatus?
  plannedPlaceOfDelivery  String?

  // --- Previous Pregnancy Complications ---
  previousPreeclampsia    Boolean?
  previousEclampsia       Boolean?
  gestationalHypertension Boolean?
  chronicHypertensionBeforePregnancy Boolean?
  previousGestationalDiabetes Boolean?
  previousPostpartumHemorrhage Boolean?
  previousPretermBirth    Boolean?
  previousLowBirthWeight  Boolean?
  previousPlacentalAbruption Boolean?
  previousPlacentaPrevia  Boolean?
  previousIufd            Boolean? // Intrauterine Fetal Death

  // --- Medical History ---
  chronicHypertension     Boolean?
  diabetesMellitus        Boolean?
  kidneyDisease           Boolean?
  heartDisease            Boolean?
  asthma                  Boolean?
  sickleCellDisease       Boolean?
  epilepsy                Boolean?
  thyroidDisease          Boolean?
  hivStatus               Boolean?
  hepatitisBStatus        Boolean?

  // --- Family History ---
  familyHypertension      Boolean?
  familyPreeclampsia      Boolean?
  familyDiabetes          Boolean?
  familyKidneyDisease     Boolean?
  familyMultiplePregnancy Boolean?

  // --- Lifestyle & Social History ---
  smokingStatus           SmokingStatus?
  alcoholUse              AlcoholUse?
  substanceUse            SubstanceUse?
  occupation              String?
  educationLevel          EducationLevel?
  distanceToFacility      Float?    // in km
  emergencyTransport      Boolean?
  supportPersonAvailable  Boolean?

  // Current Pregnancy Risk Factors
  bmi                     Float?

  // Risk History
  riskHistory             RiskHistory[]

  @@index([userId])
  @@index([facilityId])
  @@index([patientId])
  @@index([isActive])
  @@index([status])
  @@map("patient")
}

/**
 * Alert Entity
 */
model Alert {
  id         String    @id @default(uuid())
  facilityId String
  patientId  String
  type       String
  message    String
  isResolved Boolean   @default(false)
  resolvedAt DateTime?
  createdAt  DateTime  @default(now())
  updatedAt  DateTime  @updatedAt

  facility Facility @relation(fields: [facilityId], references: [id], onDelete: Cascade)
  patient  Patient  @relation(fields: [patientId], references: [id], onDelete: Cascade)

  @@index([facilityId])
  @@index([patientId])
  @@index([isResolved])
  @@map("alert")
}

/**
 * Referral Entity
 */

enum ReferralStatus {
  PENDING
  ACCEPTED
  COMPLETED
  CANCELLED
}

model Referral {
  id String @id @default(uuid())

  patientId String

  fromFacilityId String
  toFacilityId   String?

  reason String
  notes  String?

  status ReferralStatus @default(PENDING)

  referredAt  DateTime  @default(now())
  acceptedAt  DateTime?
  completedAt DateTime?

  patient Patient @relation(fields: [patientId], references: [id])

  fromFacility Facility @relation("OutgoingReferrals", fields: [fromFacilityId], references: [id])

  toFacility Facility? @relation("IncomingReferrals", fields: [toFacilityId], references: [id])

  createdAt  DateTime  @default(now())
  updatedAt  DateTime  @updatedAt
  facility   Facility? @relation(fields: [facilityId], references: [id])
  facilityId String?

  @@index([patientId])
  @@index([fromFacilityId])
  @@index([toFacilityId])
  @@index([status])
}

/**
 * User Status Enum
 */
enum UserStatus {
  PENDING
  ACTIVE
  SUSPENDED
}

/**
 * UserAuth Entity
 * CLINICAL SAFETY CONSTRAINTS:
 * - Minimal PII only (email OR phone, not both required)
 * - No health data in this table
 * - No logging of credentials
 * - Passwords are hashed (never stored in plain text)
 * DATA MINIMIZATION:
 * - Only authentication-related fields
 * - No names, addresses, or demographic data
 * - Health data stored in separate UserProfile table
 */
model UserAuth {
  id                   String    @id @default(uuid())
  email                String?   @unique
  phone                String?   @unique
  passwordHash         String? // bcrypt hashed password (null until setup)
  role                 UserRole  @default(PATIENT)
  status               UserStatus @default(PENDING)
  refreshToken         String? // For JWT refresh token rotation
  pushToken            String? // For Expo push notifications
  passwordSetupToken   String? // For initial password setup
  passwordSetupExpiresAt DateTime?
  passwordResetToken   String? // For forgot password
  passwordResetExpiresAt DateTime?
  isActive             Boolean   @default(true)
  createdAt            DateTime  @default(now())
  updatedAt            DateTime  @updatedAt

  // Relation to UserProfile (optional - created after registration)
  profile UserProfile?

  // Relation to BloodPressureReadings
  bloodPressureReadings BloodPressureReading[]

  // Relation to SymptomRecords
  symptomRecords SymptomRecord[]

  // Relation to Notifications
  notifications Notification[]

  // Relation to MonitoringStateRecord
  monitoringStateRecord MonitoringStateRecord?

  // Relation to FollowUpTasks
  followUpTasks FollowUpTask[]

  // Relation to Appointments
  appointments Appointment[]

  // Relation to HealthcareWorker
  healthcareWorker HealthcareWorker?

  // Relation to Patient
  patient Patient?

  @@index([email])
  @@index([phone])
  @@index([role])
  @@map("user_auth")
}

/**
 * Age Range Enum
 * DATA MINIMIZATION:
 * - Use age ranges instead of exact DOB
 * - Prevents unnecessary PII collection
 */
enum AgeRange {
  UNDER_18
  AGE_18_34
  AGE_35_PLUS
}

/**
 * Emergency Contact Relationship Enum
 * DATA MINIMIZATION:
 * - Relationship type only (no names stored)
 * - Supports midwife or closest relative
 */
enum EmergencyContactRelationship {
  MIDWIFE
  PARTNER
  FAMILY_MEMBER
  OTHER
}

/**
 * Known Conditions Enum
 * CLINICAL SAFETY:
 * - Enumerated list prevents free-text medical history
 * - Only high-risk pregnancy conditions relevant to hypertension
 * - No diagnostic information stored
 */
enum KnownCondition {
  CHRONIC_HYPERTENSION
  GESTATIONAL_DIABETES
  PREECLAMPSIA_HISTORY
  KIDNEY_DISEASE
  AUTOIMMUNE_DISORDER
  MULTIPLE_PREGNANCY
  NONE
}

/**
 * UserProfile Entity
 * DATA MINIMIZATION PRINCIPLES:
 * - No DOB (age range only)
 * - No address
 * - No free-text medical history
 * - No name or demographic data
 * - Only pregnancy-relevant information
 * CLINICAL SAFETY:
 * - All fields are enumerated or structured
 * - No diagnostic interpretations stored
 * - Links to UserAuth via userId
 */
model UserProfile {
  id                           String                        @id @default(uuid())
  userId                       String                        @unique
  ageRange                     AgeRange
  pregnancyWeeks               Int // Current week of pregnancy (0-42)
  firstPregnancy               Boolean
  knownConditions              KnownCondition[] // Array of enumerated conditions
  emergencyContactPhone        String? // Phone number only (no name)
  emergencyContactEmail        String? // Email address for emergency alerts
  emergencyContactRelationship EmergencyContactRelationship? // Relationship enum (e.g. MIDWIFE, PARTNER)

  // Clinic Information
  clinicName    String?
  clinicAddress String?
  clinicPhone   String?

  // Notification Preferences
  notifyCarePriority Boolean @default(true)
  notifyBpAlert      Boolean @default(true)
  notifySymptomAlert Boolean @default(true)
  notifyReminders    Boolean @default(true)
  reminderTime       String? @default("09:00") // 24h format (HH:mm)

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  // Relation to UserAuth
  userAuth UserAuth @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@index([userId])
  @@map("user_profile")
}

/**
 * Blood Pressure Reading Entity
 * CLINICAL SAFETY CONSTRAINTS:
 * - Manual entry only (no device integration)
 * - Do NOT label readings as normal/abnormal
 * - Do NOT store interpretations
 * - Neutral data handling only
 * VALIDATION:
 * - Systolic: 60-260 mmHg (physiologically possible range)
 * - Diastolic: 40-160 mmHg (physiologically possible range)
 * - Timestamp for temporal tracking
 * PURPOSE:
 * - Store raw BP measurements
 * - Used by care priority engine (Phase 3)
 * - No diagnostic labels attached to data
 */
model BloodPressureReading {
  id         String   @id @default(uuid())
  userId     String
  systolic   Int // mmHg (60-260)
  diastolic  Int // mmHg (40-160)
  recordedAt DateTime @default(now())
  createdAt  DateTime @default(now())

  // Relation to UserAuth
  userAuth UserAuth @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@index([userId])
  @@index([recordedAt])
  @@map("blood_pressure_reading")
}

/**
 * Symptom Type Enum
 * CLINICAL SAFETY:
 * - Enumerated list of pregnancy hypertension warning signs
 * - Free-text is only allowed with OTHER for user-entered symptoms
 * - No severity levels
 * - Based on clinical guidelines for preeclampsia/eclampsia
 */
enum SymptomType {
  HEADACHE // Severe or persistent headache
  BLURRED_VISION // Visual disturbances
  SWELLING // Edema (face, hands, feet)
  VAGINAL_BLEEDING // Vaginal bleeding
  FEVER // Fever
  REDUCED_FETAL_MOVEMENT // Reduced fetal movement
  DIFFICULTY_BREATHING // Difficulty breathing
  CONVULSIONS // Convulsions
  UPPER_ABDOMINAL_PAIN // Right upper quadrant pain
  REDUCED_URINE // Decreased urine output
  NAUSEA_VOMITING // Persistent nausea/vomiting
  SHORTNESS_OF_BREATH // Difficulty breathing
  OTHER // User-entered symptom text stored separately
}

/**
 * Symptom Record Entity
 * CLINICAL SAFETY CONSTRAINTS:
 * - Atomic recording (one symptom per record)
 * - No severity levels
 * - No numeric scoring
 * - No interpretation or diagnosis
 * PURPOSE:
 * - Track presence of warning symptoms
 * - Used by care priority engine for escalation
 * - Each symptom is a separate, timestamped record
 */
model SymptomRecord {
  id            String      @id @default(uuid())
  userId        String
  symptomType   SymptomType
  customSymptom String?
  recordedAt    DateTime    @default(now())
  createdAt     DateTime    @default(now())

  // Relation to UserAuth
  userAuth UserAuth @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@index([userId])
  @@index([recordedAt])
  @@index([symptomType])
  @@map("symptom_record")
}

/**
 * Notification Type Enum
 */
enum NotificationType {
  CARE_PRIORITY
  BP_ALERT
  SYMPTOM_ALERT
  REMINDER
  EDUCATIONAL
}

/**
 * Notification Priority Enum
 */
enum NotificationPriority {
  INFORMATIONAL
  EDUCATIONAL
  REMINDER
  ELEVATED_RISK
  CRITICAL
}

/**
 * Notification Category Enum
 */
enum NotificationCategory {
  PREECLAMPSIA_AWARENESS
  BP_MONITORING
  PREGNANCY_WARNING_SIGNS
  HYDRATION
  REST
  ANTENATAL_CARE
  SYMPTOM_AWARENESS
  TRIMESTER_GUIDANCE
}

/**
 * Notification Entity
 * PURPOSE:
 * - Store history of alerts and notifications
 * - Track read status
 */
model Notification {
  id        String                @id @default(uuid())
  userId    String
  type      NotificationType
  priority  NotificationPriority  @default(REMINDER)
  category  NotificationCategory?
  title     String
  message   String
  read      Boolean               @default(false)
  createdAt DateTime              @default(now())

  userAuth UserAuth @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@index([userId])
  @@index([createdAt])
  @@map("notification")
}

/**
 * MonitoringState Enum
 * Defines the possible states of the monitoring system for a user.
 */
enum MonitoringState {
  NORMAL
  MONITOR
  URGENT
  EMERGENCY
}

/**
 * MonitoringStateRecord Entity
 * Stores the current monitoring state for each user.
 */
model MonitoringStateRecord {
  id            String          @id @default(uuid())
  userId        String          @unique
  currentState  MonitoringState
  lastUpdatedAt DateTime        @default(now())
  reason        String?

  userAuth UserAuth @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@index([userId])
  @@map("monitoring_state_record")
}

/**
 * FollowUpTaskType Enum
 * Defines the types of follow-up tasks.
 */
enum FollowUpTaskType {
  RECHECK
  SEEK_CARE
}

/**
 * FollowUpTaskStatus Enum
 * Defines the status of follow-up tasks.
 */
enum FollowUpTaskStatus {
  PENDING
  COMPLETED
  MISSED
}

enum PatientStatus {
  ACTIVE
  DEFAULTER
  DELIVERED
  TRANSFERRED
  LOST_TO_FOLLOW_UP
}

/**
 * FollowUpTask Entity
 * Stores details about each follow-up task.
 */
model FollowUpTask {
  id               String             @id @default(uuid())
  userId           String
  type             FollowUpTaskType
  dueAt            DateTime
  status           FollowUpTaskStatus @default(PENDING)
  relatedReadingId String? // Optional: Link to a specific BP reading that triggered the task

  userAuth UserAuth @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@index([userId])
  @@index([dueAt])
  @@index([status])
  @@map("follow_up_task")
}

enum AppointmentType {
  ANC
  LAB
  SCAN
}

enum AppointmentStatus {
  SCHEDULED
  COMPLETED
  MISSED
}

enum UrineProtein {
  NEGATIVE
  TRACE
  PLUS_1
  PLUS_2
  PLUS_3
}

enum RiskLevel {
  LOW
  MODERATE
  HIGH
  EMERGENCY
}

model Appointment {
  id         String            @id @default(uuid())
  userId     String
  facilityId String?
  patientId  String?
  type       AppointmentType
  title      String
  dateTime   DateTime
  location   String?
  notes      String?
  status     AppointmentStatus @default(SCHEDULED)
  createdAt  DateTime          @default(now())
  updatedAt  DateTime          @updatedAt

  userAuth UserAuth  @relation(fields: [userId], references: [id], onDelete: Cascade)
  facility Facility? @relation(fields: [facilityId], references: [id], onDelete: Cascade)
  patient  Patient?  @relation(fields: [patientId], references: [id], onDelete: Cascade)

  @@index([userId])
  @@index([facilityId])
  @@index([patientId])
  @@index([dateTime])
  @@map("appointment")
}

model ANCVisit {
  id String @id @default(uuid())

  patientId String
  patient   Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)

  facilityId String
  facility   Facility @relation(fields: [facilityId], references: [id], onDelete: Cascade)

  healthcareWorkerId String
  healthcareWorker   HealthcareWorker @relation(fields: [healthcareWorkerId], references: [id], onDelete: Cascade)

  visitDate DateTime @default(now())

  gestationalAge Int?

  weight Float?

  bloodPressureSystolic  Int?
  bloodPressureDiastolic Int?

  urineProtein UrineProtein?

  fundalHeight Float?

  fetalHeartRate Int?

  fetalMovement Boolean?

  haemoglobin Float?

  temperature Float?

  remarks String?

  nextAppointmentDate DateTime?

  riskLevel RiskLevel @default(LOW)

  createdAt DateTime @default(now())

  updatedAt DateTime @updatedAt

  @@index([patientId])
  @@index([facilityId])
  @@index([healthcareWorkerId])
  @@index([visitDate])
  @@index([nextAppointmentDate])
  @@index([riskLevel])
  @@map("anc_visit")
}

model RiskHistory {
  id                    String    @id @default(uuid())
  patientId             String
  patient               Patient   @relation(fields: [patientId], references: [id], onDelete: Cascade)
  riskLevel             RiskLevel
  score                 Int
  reasons               String[]
  contributingFactorIds String[]
  recommendations       String[]
  isRedFlag             Boolean
  redFlagReasons        String[]
  calculatedAt          DateTime  @default(now())
  recordedBy            String?
  createdAt             DateTime  @default(now())
  updatedAt             DateTime  @updatedAt

  @@index([patientId])
  @@index([calculatedAt])
  @@map("risk_history")
}