shopify-sdk 1.0.0

A Rust SDK for the Shopify API
Documentation
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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
//! Session management for Shopify API authentication.
//!
//! This module provides the [`Session`] type for representing authenticated
//! sessions used in API calls, along with helper methods for session ID generation
//! and factory methods for creating sessions from OAuth responses.
//!
//! # Session Types
//!
//! Shopify supports two types of access tokens, each with its own session pattern:
//!
//! - **Offline sessions** (`is_online = false`):
//!   - App-level tokens that persist indefinitely (or until expiration for expiring tokens)
//!   - ID format: `"offline_{shop}"` (e.g., `"offline_my-store.myshopify.com"`)
//!   - May include refresh tokens for token refresh flow
//!   - Used for background tasks, webhooks, and server-side operations
//!
//! - **Online sessions** (`is_online = true`):
//!   - User-specific tokens that expire
//!   - ID format: `"{shop}_{user_id}"` (e.g., `"my-store.myshopify.com_12345"`)
//!   - Include expiration time and associated user information
//!   - Used for user-facing operations where user identity matters
//!
//! # Immutability
//!
//! Sessions are immutable after creation. To "update" a session, create a new
//! `Session` instance. This design ensures thread safety and prevents accidental
//! mutation of authentication state.
//!
//! # Example
//!
//! ```rust
//! use shopify_sdk::{Session, ShopDomain, AuthScopes};
//!
//! // Create an offline session with generated ID
//! let shop = ShopDomain::new("my-store").unwrap();
//! let session = Session::new(
//!     Session::generate_offline_id(&shop),
//!     shop,
//!     "access-token".to_string(),
//!     "read_products".parse().unwrap(),
//!     false,
//!     None,
//! );
//!
//! assert_eq!(session.id, "offline_my-store.myshopify.com");
//! assert!(session.is_active());
//! ```

use crate::auth::associated_user::AssociatedUser;
use crate::auth::AuthScopes;
use crate::config::ShopDomain;
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};

/// Buffer time (in seconds) before considering a refresh token expired.
/// Matches the Ruby SDK's behavior.
const REFRESH_TOKEN_EXPIRY_BUFFER_SECONDS: i64 = 60;

/// Represents an authenticated session for Shopify API calls.
///
/// Sessions hold the authentication state needed to make API requests on behalf
/// of a shop. They can be either online (user-specific) or offline (app-level).
///
/// # Thread Safety
///
/// `Session` is `Send + Sync`, making it safe to share across threads.
///
/// # Serialization
///
/// Sessions can be serialized to JSON for storage and deserialized when needed:
///
/// ```rust
/// use shopify_sdk::{Session, ShopDomain, AuthScopes};
///
/// let session = Session::new(
///     "session-id".to_string(),
///     ShopDomain::new("my-store").unwrap(),
///     "access-token".to_string(),
///     "read_products".parse().unwrap(),
///     false,
///     None,
/// );
///
/// // Serialize to JSON
/// let json = serde_json::to_string(&session).unwrap();
///
/// // Deserialize from JSON
/// let restored: Session = serde_json::from_str(&json).unwrap();
/// assert_eq!(session, restored);
/// ```
///
/// # Example
///
/// ```rust
/// use shopify_sdk::{Session, ShopDomain, AuthScopes};
///
/// let session = Session::new(
///     "session-id".to_string(),
///     ShopDomain::new("my-store").unwrap(),
///     "access-token".to_string(),
///     "read_products".parse().unwrap(),
///     false, // offline session
///     None,  // no expiration
/// );
///
/// assert!(session.is_active());
/// assert!(!session.expired());
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Session {
    /// Unique identifier for this session.
    ///
    /// For offline sessions: `"offline_{shop}"` (e.g., `"offline_my-store.myshopify.com"`)
    /// For online sessions: `"{shop}_{user_id}"` (e.g., `"my-store.myshopify.com_12345"`)
    pub id: String,

    /// The shop this session is for.
    pub shop: ShopDomain,

    /// The access token for API authentication.
    pub access_token: String,

    /// The OAuth scopes granted to this session.
    pub scopes: AuthScopes,

    /// Whether this is an online (user-specific) session.
    pub is_online: bool,

    /// When this session expires, if applicable.
    ///
    /// Offline sessions have `None` (they don't expire) unless using expiring tokens.
    /// Online sessions have a specific expiration time.
    pub expires: Option<DateTime<Utc>>,

    /// OAuth state parameter, if applicable.
    ///
    /// Used during the OAuth flow for CSRF protection.
    pub state: Option<String>,

    /// Shopify-provided session ID, if applicable.
    pub shopify_session_id: Option<String>,

    /// User information for online sessions.
    ///
    /// Only present for online sessions (when `is_online` is `true`).
    pub associated_user: Option<AssociatedUser>,

    /// User-specific scopes for online sessions.
    ///
    /// These may be different from the app's granted scopes, representing
    /// what the specific user is allowed to do.
    pub associated_user_scopes: Option<AuthScopes>,

    /// The refresh token for obtaining new access tokens.
    ///
    /// Only present for expiring offline tokens. Use with [`refresh_access_token`]
    /// to obtain a new access token before the current one expires.
    ///
    /// [`refresh_access_token`]: crate::auth::oauth::refresh_access_token
    #[serde(default)]
    pub refresh_token: Option<String>,

    /// When the refresh token expires, if applicable.
    ///
    /// `None` indicates the refresh token does not expire or is not present.
    /// Use [`refresh_token_expired`](Session::refresh_token_expired) to check
    /// if the refresh token needs to be renewed.
    #[serde(default)]
    pub refresh_token_expires_at: Option<DateTime<Utc>>,
}

impl Session {
    /// Creates a new session with the specified parameters.
    ///
    /// This constructor maintains backward compatibility with existing code.
    /// New fields (`associated_user`, `associated_user_scopes`, `refresh_token`,
    /// and `refresh_token_expires_at`) default to `None`.
    ///
    /// For online sessions with user information, use [`Session::with_user`] instead.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique session identifier
    /// * `shop` - The shop domain
    /// * `access_token` - The access token for API calls
    /// * `scopes` - OAuth scopes granted to this session
    /// * `is_online` - Whether this is a user-specific session
    /// * `expires` - When this session expires (None for offline sessions)
    ///
    /// # Example
    ///
    /// ```rust
    /// use shopify_sdk::{Session, ShopDomain, AuthScopes};
    ///
    /// let session = Session::new(
    ///     "offline_my-store.myshopify.com".to_string(),
    ///     ShopDomain::new("my-store").unwrap(),
    ///     "access-token".to_string(),
    ///     "read_products".parse().unwrap(),
    ///     false,
    ///     None,
    /// );
    /// ```
    #[must_use]
    pub const fn new(
        id: String,
        shop: ShopDomain,
        access_token: String,
        scopes: AuthScopes,
        is_online: bool,
        expires: Option<DateTime<Utc>>,
    ) -> Self {
        Self {
            id,
            shop,
            access_token,
            scopes,
            is_online,
            expires,
            state: None,
            shopify_session_id: None,
            associated_user: None,
            associated_user_scopes: None,
            refresh_token: None,
            refresh_token_expires_at: None,
        }
    }

    /// Creates a new online session with associated user information.
    ///
    /// This is a convenience constructor for online sessions that includes
    /// user details and user-specific scopes.
    ///
    /// # Arguments
    ///
    /// * `id` - Unique session identifier (typically `"{shop}_{user_id}"`)
    /// * `shop` - The shop domain
    /// * `access_token` - The access token for API calls
    /// * `scopes` - OAuth scopes granted to this session
    /// * `expires` - When this session expires
    /// * `associated_user` - The user who authorized this session
    /// * `associated_user_scopes` - User-specific scopes (if different from app scopes)
    ///
    /// # Example
    ///
    /// ```rust
    /// use shopify_sdk::{Session, ShopDomain, AuthScopes, AssociatedUser};
    /// use chrono::{Utc, Duration};
    ///
    /// let shop = ShopDomain::new("my-store").unwrap();
    /// let user = AssociatedUser::new(
    ///     12345,
    ///     "Jane".to_string(),
    ///     "Doe".to_string(),
    ///     "jane@example.com".to_string(),
    ///     true, true, "en".to_string(), false,
    /// );
    ///
    /// let session = Session::with_user(
    ///     Session::generate_online_id(&shop, 12345),
    ///     shop,
    ///     "access-token".to_string(),
    ///     "read_products".parse().unwrap(),
    ///     Some(Utc::now() + Duration::hours(1)),
    ///     user,
    ///     Some("read_products".parse().unwrap()),
    /// );
    ///
    /// assert!(session.is_online);
    /// assert!(session.associated_user.is_some());
    /// ```
    #[must_use]
    #[allow(clippy::too_many_arguments)]
    pub const fn with_user(
        id: String,
        shop: ShopDomain,
        access_token: String,
        scopes: AuthScopes,
        expires: Option<DateTime<Utc>>,
        associated_user: AssociatedUser,
        associated_user_scopes: Option<AuthScopes>,
    ) -> Self {
        Self {
            id,
            shop,
            access_token,
            scopes,
            is_online: true,
            expires,
            state: None,
            shopify_session_id: None,
            associated_user: Some(associated_user),
            associated_user_scopes,
            refresh_token: None,
            refresh_token_expires_at: None,
        }
    }

    /// Generates a session ID for an offline session.
    ///
    /// The ID format is `"offline_{shop}"` where `{shop}` is the full shop domain.
    ///
    /// # Example
    ///
    /// ```rust
    /// use shopify_sdk::{Session, ShopDomain};
    ///
    /// let shop = ShopDomain::new("my-store").unwrap();
    /// let id = Session::generate_offline_id(&shop);
    /// assert_eq!(id, "offline_my-store.myshopify.com");
    /// ```
    #[must_use]
    pub fn generate_offline_id(shop: &ShopDomain) -> String {
        format!("offline_{}", shop.as_ref())
    }

    /// Generates a session ID for an online session.
    ///
    /// The ID format is `"{shop}_{user_id}"` where `{shop}` is the full shop domain
    /// and `{user_id}` is the Shopify user ID.
    ///
    /// # Example
    ///
    /// ```rust
    /// use shopify_sdk::{Session, ShopDomain};
    ///
    /// let shop = ShopDomain::new("my-store").unwrap();
    /// let id = Session::generate_online_id(&shop, 12345);
    /// assert_eq!(id, "my-store.myshopify.com_12345");
    /// ```
    #[must_use]
    pub fn generate_online_id(shop: &ShopDomain, user_id: u64) -> String {
        format!("{}_{}", shop.as_ref(), user_id)
    }

    /// Creates a session from an OAuth access token response.
    ///
    /// This factory method automatically:
    /// - Generates the appropriate session ID based on session type
    /// - Parses scopes from the response
    /// - Calculates expiration time from `expires_in` seconds
    /// - Sets `is_online` based on presence of associated user
    /// - Populates refresh token fields if present in the response
    ///
    /// # Arguments
    ///
    /// * `shop` - The shop domain
    /// * `response` - The OAuth access token response from Shopify
    ///
    /// # Example
    ///
    /// ```rust
    /// use shopify_sdk::{Session, ShopDomain};
    /// use shopify_sdk::auth::session::AccessTokenResponse;
    ///
    /// let shop = ShopDomain::new("my-store").unwrap();
    /// let response = AccessTokenResponse {
    ///     access_token: "access-token".to_string(),
    ///     scope: "read_products,write_orders".to_string(),
    ///     expires_in: None,
    ///     associated_user_scope: None,
    ///     associated_user: None,
    ///     session: None,
    ///     refresh_token: None,
    ///     refresh_token_expires_in: None,
    /// };
    ///
    /// let session = Session::from_access_token_response(shop, &response);
    /// assert!(!session.is_online);
    /// assert_eq!(session.id, "offline_my-store.myshopify.com");
    /// ```
    #[must_use]
    pub fn from_access_token_response(shop: ShopDomain, response: &AccessTokenResponse) -> Self {
        let is_online = response.associated_user.is_some();

        let id = response.associated_user.as_ref().map_or_else(
            || Self::generate_offline_id(&shop),
            |user| Self::generate_online_id(&shop, user.id),
        );

        let scopes: AuthScopes = response.scope.parse().unwrap_or_default();

        let expires = response
            .expires_in
            .map(|secs| Utc::now() + Duration::seconds(i64::from(secs)));

        let associated_user_scopes = response
            .associated_user_scope
            .as_ref()
            .and_then(|s| s.parse().ok());

        let associated_user = response.associated_user.as_ref().map(|u| AssociatedUser {
            id: u.id,
            first_name: u.first_name.clone(),
            last_name: u.last_name.clone(),
            email: u.email.clone(),
            email_verified: u.email_verified,
            account_owner: u.account_owner,
            locale: u.locale.clone(),
            collaborator: u.collaborator,
        });

        let refresh_token = response.refresh_token.clone();

        let refresh_token_expires_at = response
            .refresh_token_expires_in
            .map(|secs| Utc::now() + Duration::seconds(i64::from(secs)));

        Self {
            id,
            shop,
            access_token: response.access_token.clone(),
            scopes,
            is_online,
            expires,
            state: None,
            shopify_session_id: response.session.clone(),
            associated_user,
            associated_user_scopes,
            refresh_token,
            refresh_token_expires_at,
        }
    }

    /// Returns `true` if this session has expired.
    ///
    /// Sessions without an expiration time are considered never expired.
    #[must_use]
    pub fn expired(&self) -> bool {
        self.expires.is_some_and(|expires| Utc::now() > expires)
    }

    /// Returns `true` if this session is active (not expired and has access token).
    #[must_use]
    pub fn is_active(&self) -> bool {
        !self.access_token.is_empty() && !self.expired()
    }

    /// Returns `true` if the refresh token has expired or will expire within 60 seconds.
    ///
    /// This method uses a 60-second buffer (matching the Ruby SDK) to ensure
    /// you have time to refresh the token before it actually expires.
    ///
    /// Returns `false` if:
    /// - No `refresh_token_expires_at` is set (token doesn't expire)
    /// - The refresh token has more than 60 seconds before expiration
    ///
    /// # Example
    ///
    /// ```rust
    /// use shopify_sdk::{Session, ShopDomain, AuthScopes};
    /// use chrono::{Utc, Duration};
    ///
    /// // Session without refresh token expiration
    /// let session = Session::new(
    ///     "session-id".to_string(),
    ///     ShopDomain::new("my-store").unwrap(),
    ///     "access-token".to_string(),
    ///     AuthScopes::new(),
    ///     false,
    ///     None,
    /// );
    /// assert!(!session.refresh_token_expired());
    /// ```
    #[must_use]
    pub fn refresh_token_expired(&self) -> bool {
        self.refresh_token_expires_at.is_some_and(|expires_at| {
            let buffer = Duration::seconds(REFRESH_TOKEN_EXPIRY_BUFFER_SECONDS);
            Utc::now() + buffer > expires_at
        })
    }
}

/// OAuth access token response from Shopify.
///
/// This struct represents the response from Shopify's OAuth token endpoint.
/// It is used with [`Session::from_access_token_response`] to create sessions.
///
/// Note: This struct is defined here temporarily and may be moved to an
/// OAuth module in a future release.
#[derive(Clone, Debug, Deserialize)]
pub struct AccessTokenResponse {
    /// The access token for API calls.
    pub access_token: String,

    /// Comma-separated list of granted scopes.
    pub scope: String,

    /// Number of seconds until the token expires (online tokens only).
    pub expires_in: Option<u32>,

    /// Comma-separated list of user-specific scopes (online tokens only).
    pub associated_user_scope: Option<String>,

    /// Associated user information (online tokens only).
    pub associated_user: Option<AssociatedUserResponse>,

    /// Shopify-provided session ID.
    #[serde(rename = "session")]
    pub session: Option<String>,

    /// The refresh token for obtaining new access tokens.
    ///
    /// Only present for expiring offline tokens.
    pub refresh_token: Option<String>,

    /// Number of seconds until the refresh token expires.
    ///
    /// Only present for expiring offline tokens.
    pub refresh_token_expires_in: Option<u32>,
}

/// User information from an OAuth access token response.
///
/// This struct matches the format of user data in Shopify's OAuth response.
#[derive(Clone, Debug, Deserialize)]
pub struct AssociatedUserResponse {
    /// The Shopify user ID.
    pub id: u64,

    /// The user's first name.
    pub first_name: String,

    /// The user's last name.
    pub last_name: String,

    /// The user's email address.
    pub email: String,

    /// Whether the user's email has been verified.
    pub email_verified: bool,

    /// Whether the user is the account owner.
    pub account_owner: bool,

    /// The user's locale preference.
    pub locale: String,

    /// Whether the user is a collaborator.
    pub collaborator: bool,
}

// Verify Session is Send + Sync at compile time
const _: fn() = || {
    const fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<Session>();
};

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_shop() -> ShopDomain {
        ShopDomain::new("my-store").unwrap()
    }

    fn sample_scopes() -> AuthScopes {
        "read_products,write_orders".parse().unwrap()
    }

    fn sample_user() -> AssociatedUser {
        AssociatedUser::new(
            12345,
            "Jane".to_string(),
            "Doe".to_string(),
            "jane@example.com".to_string(),
            true,
            true,
            "en".to_string(),
            false,
        )
    }

    // === Existing Session tests ===

    #[test]
    fn test_session_expired() {
        // Expired session
        let expired = Session::new(
            "id".to_string(),
            ShopDomain::new("shop").unwrap(),
            "token".to_string(),
            AuthScopes::new(),
            false,
            Some(Utc::now() - Duration::hours(1)),
        );
        assert!(expired.expired());

        // Not expired session
        let valid = Session::new(
            "id".to_string(),
            ShopDomain::new("shop").unwrap(),
            "token".to_string(),
            AuthScopes::new(),
            false,
            Some(Utc::now() + Duration::hours(1)),
        );
        assert!(!valid.expired());

        // No expiration
        let no_expiry = Session::new(
            "id".to_string(),
            ShopDomain::new("shop").unwrap(),
            "token".to_string(),
            AuthScopes::new(),
            false,
            None,
        );
        assert!(!no_expiry.expired());
    }

    #[test]
    fn test_session_is_active() {
        // Active session
        let active = Session::new(
            "id".to_string(),
            ShopDomain::new("shop").unwrap(),
            "token".to_string(),
            AuthScopes::new(),
            false,
            None,
        );
        assert!(active.is_active());

        // Inactive due to empty token
        let no_token = Session::new(
            "id".to_string(),
            ShopDomain::new("shop").unwrap(),
            String::new(),
            AuthScopes::new(),
            false,
            None,
        );
        assert!(!no_token.is_active());

        // Inactive due to expiration
        let expired = Session::new(
            "id".to_string(),
            ShopDomain::new("shop").unwrap(),
            "token".to_string(),
            AuthScopes::new(),
            false,
            Some(Utc::now() - Duration::hours(1)),
        );
        assert!(!expired.is_active());
    }

    #[test]
    fn test_session_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<Session>();
    }

    // === Task Group 3: Extended Session tests ===

    #[test]
    fn test_session_with_associated_user_field() {
        let user = sample_user();
        let session = Session::with_user(
            "test-session".to_string(),
            sample_shop(),
            "access-token".to_string(),
            sample_scopes(),
            Some(Utc::now() + Duration::hours(1)),
            user.clone(),
            None,
        );

        assert!(session.associated_user.is_some());
        let stored_user = session.associated_user.unwrap();
        assert_eq!(stored_user.id, 12345);
        assert_eq!(stored_user.first_name, "Jane");
        assert_eq!(stored_user.email, "jane@example.com");
    }

    #[test]
    fn test_session_with_associated_user_scopes_field() {
        let user = sample_user();
        let user_scopes: AuthScopes = "read_products".parse().unwrap();

        let session = Session::with_user(
            "test-session".to_string(),
            sample_shop(),
            "access-token".to_string(),
            sample_scopes(),
            None,
            user,
            Some(user_scopes.clone()),
        );

        assert!(session.associated_user_scopes.is_some());
        let stored_scopes = session.associated_user_scopes.unwrap();
        assert!(stored_scopes.iter().any(|s| s == "read_products"));
    }

    #[test]
    fn test_session_serialization_to_json() {
        let session = Session::new(
            "offline_my-store.myshopify.com".to_string(),
            sample_shop(),
            "access-token".to_string(),
            sample_scopes(),
            false,
            None,
        );

        let json = serde_json::to_string(&session).unwrap();
        assert!(json.contains("offline_my-store.myshopify.com"));
        assert!(json.contains("access-token"));
        assert!(json.contains("my-store.myshopify.com"));
    }

    #[test]
    fn test_session_deserialization_from_json() {
        let json = r#"{
            "id": "test-session",
            "shop": "test-shop.myshopify.com",
            "access_token": "token123",
            "scopes": "read_products",
            "is_online": false,
            "expires": null,
            "state": null,
            "shopify_session_id": null,
            "associated_user": null,
            "associated_user_scopes": null
        }"#;

        let session: Session = serde_json::from_str(json).unwrap();
        assert_eq!(session.id, "test-session");
        assert_eq!(session.access_token, "token123");
        assert!(!session.is_online);
        assert!(session.associated_user.is_none());
        // Verify refresh token fields default to None
        assert!(session.refresh_token.is_none());
        assert!(session.refresh_token_expires_at.is_none());
    }

    #[test]
    fn test_session_equality_comparison() {
        let session1 = Session::new(
            "id".to_string(),
            sample_shop(),
            "token".to_string(),
            sample_scopes(),
            false,
            None,
        );

        let session2 = Session::new(
            "id".to_string(),
            sample_shop(),
            "token".to_string(),
            sample_scopes(),
            false,
            None,
        );

        assert_eq!(session1, session2);

        // Different ID should not be equal
        let session3 = Session::new(
            "different-id".to_string(),
            sample_shop(),
            "token".to_string(),
            sample_scopes(),
            false,
            None,
        );

        assert_ne!(session1, session3);
    }

    #[test]
    fn test_session_clone_preserves_all_fields() {
        let user = sample_user();
        let session = Session::with_user(
            "test-id".to_string(),
            sample_shop(),
            "token".to_string(),
            sample_scopes(),
            Some(Utc::now() + Duration::hours(1)),
            user,
            Some("read_products".parse().unwrap()),
        );

        let cloned = session.clone();

        assert_eq!(session.id, cloned.id);
        assert_eq!(session.shop, cloned.shop);
        assert_eq!(session.access_token, cloned.access_token);
        assert_eq!(session.scopes, cloned.scopes);
        assert_eq!(session.is_online, cloned.is_online);
        assert_eq!(session.expires, cloned.expires);
        assert_eq!(session.associated_user, cloned.associated_user);
        assert_eq!(
            session.associated_user_scopes,
            cloned.associated_user_scopes
        );
    }

    // === Task Group 4: ID Generation and Factory Method tests ===

    #[test]
    fn test_generate_offline_id_produces_correct_format() {
        let shop = ShopDomain::new("my-store").unwrap();
        let id = Session::generate_offline_id(&shop);
        assert_eq!(id, "offline_my-store.myshopify.com");
    }

    #[test]
    fn test_generate_online_id_produces_correct_format() {
        let shop = ShopDomain::new("my-store").unwrap();
        let id = Session::generate_online_id(&shop, 12345);
        assert_eq!(id, "my-store.myshopify.com_12345");
    }

    #[test]
    fn test_from_access_token_response_with_offline_response() {
        let shop = ShopDomain::new("my-store").unwrap();
        let response = AccessTokenResponse {
            access_token: "offline-token".to_string(),
            scope: "read_products,write_orders".to_string(),
            expires_in: None,
            associated_user_scope: None,
            associated_user: None,
            session: None,
            refresh_token: None,
            refresh_token_expires_in: None,
        };

        let session = Session::from_access_token_response(shop, &response);

        assert!(!session.is_online);
        assert_eq!(session.id, "offline_my-store.myshopify.com");
        assert_eq!(session.access_token, "offline-token");
        assert!(session.associated_user.is_none());
        assert!(session.expires.is_none());
    }

    #[test]
    fn test_from_access_token_response_with_online_response() {
        let shop = ShopDomain::new("my-store").unwrap();
        let response = AccessTokenResponse {
            access_token: "online-token".to_string(),
            scope: "read_products".to_string(),
            expires_in: Some(3600),
            associated_user_scope: Some("read_products".to_string()),
            associated_user: Some(AssociatedUserResponse {
                id: 12345,
                first_name: "Jane".to_string(),
                last_name: "Doe".to_string(),
                email: "jane@example.com".to_string(),
                email_verified: true,
                account_owner: true,
                locale: "en".to_string(),
                collaborator: false,
            }),
            session: Some("shopify-session-id".to_string()),
            refresh_token: None,
            refresh_token_expires_in: None,
        };

        let session = Session::from_access_token_response(shop, &response);

        assert!(session.is_online);
        assert_eq!(session.id, "my-store.myshopify.com_12345");
        assert_eq!(session.access_token, "online-token");
        assert!(session.associated_user.is_some());
        assert!(session.expires.is_some());
        assert_eq!(
            session.shopify_session_id,
            Some("shopify-session-id".to_string())
        );

        let user = session.associated_user.unwrap();
        assert_eq!(user.id, 12345);
        assert_eq!(user.email, "jane@example.com");
    }

    #[test]
    fn test_from_access_token_response_calculates_expires() {
        let shop = ShopDomain::new("my-store").unwrap();
        let response = AccessTokenResponse {
            access_token: "token".to_string(),
            scope: "read_products".to_string(),
            expires_in: Some(3600), // 1 hour
            associated_user_scope: None,
            associated_user: Some(AssociatedUserResponse {
                id: 1,
                first_name: "Test".to_string(),
                last_name: "User".to_string(),
                email: "test@example.com".to_string(),
                email_verified: true,
                account_owner: false,
                locale: "en".to_string(),
                collaborator: false,
            }),
            session: None,
            refresh_token: None,
            refresh_token_expires_in: None,
        };

        let before = Utc::now();
        let session = Session::from_access_token_response(shop, &response);
        let after = Utc::now();

        assert!(session.expires.is_some());
        let expires = session.expires.unwrap();

        // Expires should be roughly 1 hour from now
        let expected_min = before + Duration::seconds(3600);
        let expected_max = after + Duration::seconds(3600);

        assert!(expires >= expected_min && expires <= expected_max);
    }

    #[test]
    fn test_from_access_token_response_parses_scopes() {
        let shop = ShopDomain::new("my-store").unwrap();
        let response = AccessTokenResponse {
            access_token: "token".to_string(),
            scope: "read_products,write_orders".to_string(),
            expires_in: None,
            associated_user_scope: None,
            associated_user: None,
            session: None,
            refresh_token: None,
            refresh_token_expires_in: None,
        };

        let session = Session::from_access_token_response(shop, &response);

        assert!(session.scopes.iter().any(|s| s == "read_products"));
        assert!(session.scopes.iter().any(|s| s == "write_orders"));
        // write_orders implies read_orders
        assert!(session.scopes.iter().any(|s| s == "read_orders"));
    }

    #[test]
    fn test_from_access_token_response_sets_is_online_correctly() {
        let shop = ShopDomain::new("my-store").unwrap();

        // Offline response
        let offline_response = AccessTokenResponse {
            access_token: "token".to_string(),
            scope: "read_products".to_string(),
            expires_in: None,
            associated_user_scope: None,
            associated_user: None,
            session: None,
            refresh_token: None,
            refresh_token_expires_in: None,
        };
        let offline_session = Session::from_access_token_response(shop.clone(), &offline_response);
        assert!(!offline_session.is_online);

        // Online response
        let online_response = AccessTokenResponse {
            access_token: "token".to_string(),
            scope: "read_products".to_string(),
            expires_in: Some(3600),
            associated_user_scope: None,
            associated_user: Some(AssociatedUserResponse {
                id: 1,
                first_name: "Test".to_string(),
                last_name: "User".to_string(),
                email: "test@example.com".to_string(),
                email_verified: true,
                account_owner: false,
                locale: "en".to_string(),
                collaborator: false,
            }),
            session: None,
            refresh_token: None,
            refresh_token_expires_in: None,
        };
        let online_session = Session::from_access_token_response(shop, &online_response);
        assert!(online_session.is_online);
    }

    // === Refresh token tests ===

    #[test]
    fn test_session_serialization_includes_refresh_token_field() {
        let mut session = Session::new(
            "offline_my-store.myshopify.com".to_string(),
            sample_shop(),
            "access-token".to_string(),
            sample_scopes(),
            false,
            None,
        );
        session.refresh_token = Some("refresh-token-123".to_string());

        let json = serde_json::to_string(&session).unwrap();
        assert!(json.contains("refresh_token"));
        assert!(json.contains("refresh-token-123"));
    }

    #[test]
    fn test_session_serialization_includes_refresh_token_expires_at_field() {
        let mut session = Session::new(
            "offline_my-store.myshopify.com".to_string(),
            sample_shop(),
            "access-token".to_string(),
            sample_scopes(),
            false,
            None,
        );
        session.refresh_token_expires_at = Some(Utc::now() + Duration::days(30));

        let json = serde_json::to_string(&session).unwrap();
        assert!(json.contains("refresh_token_expires_at"));
    }

    #[test]
    fn test_session_deserialization_handles_missing_refresh_token_fields_backward_compat() {
        // Old format without refresh token fields
        let json = r#"{
            "id": "test-session",
            "shop": "test-shop.myshopify.com",
            "access_token": "token123",
            "scopes": "read_products",
            "is_online": false,
            "expires": null,
            "state": null,
            "shopify_session_id": null,
            "associated_user": null,
            "associated_user_scopes": null
        }"#;

        let session: Session = serde_json::from_str(json).unwrap();
        assert!(session.refresh_token.is_none());
        assert!(session.refresh_token_expires_at.is_none());
    }

    #[test]
    fn test_refresh_token_expired_returns_false_when_expires_at_is_none() {
        let session = Session::new(
            "id".to_string(),
            sample_shop(),
            "token".to_string(),
            sample_scopes(),
            false,
            None,
        );
        assert!(!session.refresh_token_expired());
    }

    #[test]
    fn test_refresh_token_expired_returns_false_when_expires_at_is_in_future_more_than_60s() {
        let mut session = Session::new(
            "id".to_string(),
            sample_shop(),
            "token".to_string(),
            sample_scopes(),
            false,
            None,
        );
        // Set refresh token expires at 2 hours from now (well past 60 second buffer)
        session.refresh_token_expires_at = Some(Utc::now() + Duration::hours(2));

        assert!(!session.refresh_token_expired());
    }

    #[test]
    fn test_refresh_token_expired_returns_true_when_expires_at_is_within_60_seconds() {
        let mut session = Session::new(
            "id".to_string(),
            sample_shop(),
            "token".to_string(),
            sample_scopes(),
            false,
            None,
        );
        // Set refresh token expires at 30 seconds from now (within 60 second buffer)
        session.refresh_token_expires_at = Some(Utc::now() + Duration::seconds(30));

        assert!(session.refresh_token_expired());
    }

    #[test]
    fn test_refresh_token_expired_returns_true_when_already_expired() {
        let mut session = Session::new(
            "id".to_string(),
            sample_shop(),
            "token".to_string(),
            sample_scopes(),
            false,
            None,
        );
        // Set refresh token expires at 1 hour ago
        session.refresh_token_expires_at = Some(Utc::now() - Duration::hours(1));

        assert!(session.refresh_token_expired());
    }

    #[test]
    fn test_from_access_token_response_populates_refresh_token_fields() {
        let shop = ShopDomain::new("my-store").unwrap();
        let response = AccessTokenResponse {
            access_token: "access-token".to_string(),
            scope: "read_products".to_string(),
            expires_in: Some(86400), // 24 hours
            associated_user_scope: None,
            associated_user: None,
            session: None,
            refresh_token: Some("refresh-token-xyz".to_string()),
            refresh_token_expires_in: Some(2592000), // 30 days
        };

        let before = Utc::now();
        let session = Session::from_access_token_response(shop, &response);
        let after = Utc::now();

        assert_eq!(session.refresh_token, Some("refresh-token-xyz".to_string()));
        assert!(session.refresh_token_expires_at.is_some());

        let expires_at = session.refresh_token_expires_at.unwrap();
        let expected_min = before + Duration::seconds(2592000);
        let expected_max = after + Duration::seconds(2592000);

        assert!(expires_at >= expected_min && expires_at <= expected_max);
    }

    #[test]
    fn test_access_token_response_deserializes_refresh_token_field() {
        let json = r#"{
            "access_token": "test-token",
            "scope": "read_products",
            "refresh_token": "refresh-abc"
        }"#;

        let response: AccessTokenResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.refresh_token, Some("refresh-abc".to_string()));
    }

    #[test]
    fn test_access_token_response_deserializes_refresh_token_expires_in_field() {
        let json = r#"{
            "access_token": "test-token",
            "scope": "read_products",
            "refresh_token_expires_in": 2592000
        }"#;

        let response: AccessTokenResponse = serde_json::from_str(json).unwrap();
        assert_eq!(response.refresh_token_expires_in, Some(2592000));
    }

    #[test]
    fn test_access_token_response_handles_missing_optional_refresh_token_fields() {
        let json = r#"{
            "access_token": "test-token",
            "scope": "read_products"
        }"#;

        let response: AccessTokenResponse = serde_json::from_str(json).unwrap();
        assert!(response.refresh_token.is_none());
        assert!(response.refresh_token_expires_in.is_none());
    }

    #[test]
    fn test_refresh_token_expired_at_boundary_61_seconds_is_false() {
        // Use 61 seconds to avoid timing issues (1 second buffer)
        let mut session = Session::new(
            "id".to_string(),
            sample_shop(),
            "token".to_string(),
            sample_scopes(),
            false,
            None,
        );
        // Set refresh token expires at 61 seconds from now (just past buffer)
        session.refresh_token_expires_at = Some(Utc::now() + Duration::seconds(61));

        // Should NOT be expired (61 > 60)
        assert!(!session.refresh_token_expired());
    }

    #[test]
    fn test_refresh_token_expired_at_58_seconds_is_true() {
        // Use 58 seconds to avoid timing issues (within buffer)
        let mut session = Session::new(
            "id".to_string(),
            sample_shop(),
            "token".to_string(),
            sample_scopes(),
            false,
            None,
        );
        // Set refresh token expires at 58 seconds from now (within buffer)
        session.refresh_token_expires_at = Some(Utc::now() + Duration::seconds(58));

        // Should be expired (58 < 60)
        assert!(session.refresh_token_expired());
    }

    #[test]
    fn test_session_roundtrip_serialization_with_refresh_token() {
        let mut original = Session::new(
            "offline_test-shop.myshopify.com".to_string(),
            sample_shop(),
            "access-token-123".to_string(),
            sample_scopes(),
            false,
            None,
        );
        original.refresh_token = Some("refresh-token-xyz".to_string());
        original.refresh_token_expires_at = Some(Utc::now() + Duration::days(30));

        let json = serde_json::to_string(&original).unwrap();
        let restored: Session = serde_json::from_str(&json).unwrap();

        assert_eq!(original.refresh_token, restored.refresh_token);
        assert_eq!(
            original.refresh_token_expires_at,
            restored.refresh_token_expires_at
        );
    }
}