myid 0.1.9

Rust client library for MyID SDK API — user identification and verification
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
//! MyID SDK konfiguratsiya moduli.
//!
//! Ushbu modul MyID klientini ishga tushirish uchun kerak bo'ladigan
//! konfiguratsiyani boshqaradi. Barcha parametrlar [`Config::new()`] yoki
//! [`Config::from_env()`] orqali yaratiladi va `with_*()` metodlari bilan sozlanadi.
//!
//! # Arxitektura
//!
//! ```text
//! Config::new(base_url, client_id, client_secret)
//!     │                                           Config::from_env(prefix)
//!     ├── parse_url()  ← URL validatsiya               │
//!     ├── normalize_url() ← trailing slash             ├── .env fayl yuklash (dotenvy)
//!     └── default qiymatlar                            ├── env o'zgaruvchilarini o'qish
//!           │                                          └── parse_url() + normalize_url()
//!           ├── .with_timeout()           ← ixtiyoriy
//!           ├── .with_connect_timeout()   ← ixtiyoriy
//!           ├── .with_user_agent()        ← ixtiyoriy
//!           └── .with_proxy()             ← ixtiyoriy
//! ```
//!
//! # Misollar
//!
//! ## Minimal konfiguratsiya
//!
//! ```rust
//! use myid::config::Config;
//! # use myid::error::MyIdResult;
//!
//! # fn main() -> MyIdResult<()> {
//! let config = Config::new(
//!     "https://myid.uz",
//!     "your_client_id",
//!     "your_client_secret",
//! )?;
//!
//! assert_eq!(config.base_url(), "https://myid.uz/");
//! assert_eq!(config.user_agent(), "myid-client-rust/0.1");
//! # Ok(())
//! # }
//! ```
//!
//! ## To'liq konfiguratsiya
//!
//! ```rust
//! use std::time::Duration;
//! use myid::config::Config;
//! # use myid::error::MyIdResult;
//!
//! # fn main() -> MyIdResult<()> {
//! let config = Config::new("https://myid.uz", "client_id", "client_secret")?
//!     .with_timeout(Duration::from_secs(30))
//!     .with_connect_timeout(Duration::from_secs(5))
//!     .with_user_agent("my-backend/1.0")
//!     .with_proxy("http://proxy.corp.local:8080")?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Environment o'zgaruvchilaridan yuklash
//!
//! ```rust,no_run
//! use myid::config::Config;
//! # use myid::error::MyIdResult;
//!
//! # fn main() -> MyIdResult<()> {
//! // .env fayldan yoki environment'dan yuklaydi
//! let config = Config::from_env(None)?; // MYID_ prefiksi
//! # Ok(())
//! # }
//! ```
//!
//! ## Xato holatlari
//!
//! ```rust
//! use myid::config::Config;
//!
//! // Noto'g'ri URL — xato qaytaradi
//! assert!(Config::new("not-a-url", "id", "secret").is_err());
//!
//! // FTP scheme — faqat http/https qabul qilinadi
//! assert!(Config::new("ftp://example.uz", "id", "secret").is_err());
//! ```

use std::{borrow::Cow, env, fmt, time::Duration};
use url::Url;

use crate::error::{MyIdError, MyIdResult};

/// TCP/TLS ulanish uchun default timeout — **2 soniya** (2000 ms).
///
/// Agar server 2 soniya ichida TCP/TLS handshake'ni tugatmasa,
/// ulanish bekor qilinadi. [`Config::with_connect_timeout()`] orqali o'zgartirish mumkin.
pub const DEFAULT_CONNECT_TIMEOUT_MS: u64 = 2_000;

/// Butun HTTP so'rov uchun default timeout — **15 soniya** (15000 ms).
///
/// Bu vaqt ichida server javob bermasa, so'rov bekor qilinadi.
/// [`Config::with_timeout()`] orqali o'zgartirish mumkin.
pub const DEFAULT_TIMEOUT_MS: u64 = 15_000;

/// Default User-Agent sarlavhasi.
///
/// HTTP so'rovlarda `User-Agent` header sifatida yuboriladi.
/// Observability va diagnostika uchun ishlatiladi.
pub(crate) const DEFAULT_USER_AGENT: &str = "myid-client-rust/0.1";

/// Environment o'zgaruvchilari uchun default prefiks.
///
/// [`Config::from_env()`] metodi uchun ishlatiladi.
/// Masalan: `MYID_BASE_URL`, `MYID_CLIENT_ID`, `MYID_CLIENT_SECRET`.
pub(crate) const DEFAULT_PREFIX: &str = "MYID_";

// Compile-time kafolat: Config xavfsiz tarzda threadlar orasida
// share qilinishi mumkin. Agar kelajakda `Rc` yoki boshqa
// `!Send` tur qo'shilsa, kompilatsiya xato beradi.
const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<Config>();
};

/// MyID SDK ning asosiy konfiguratsiya strukturasi.
///
/// `Config` MyID API bilan ishlash uchun kerakli barcha parametrlarni
/// o'z ichiga oladi: API URL, OAuth credential'lar, timeout'lar,
/// va ixtiyoriy proxy sozlamalari.
///
/// # Yaratish
///
/// Ikki usulda yaratiladi:
///
/// 1. **To'g'ridan-to'g'ri** — [`Config::new()`] orqali
/// 2. **Environment'dan** — [`Config::from_env()`] orqali (`.env` fayl qo'llab-quvvatlanadi)
///
/// ```rust
/// # use myid::config::Config;
/// # use myid::error::MyIdResult;
/// # fn main() -> MyIdResult<()> {
/// let config = Config::new("https://myid.uz", "client_id", "secret")?;
/// # Ok(())
/// # }
/// ```
///
/// # Ixtiyoriy parametrlar
///
/// `with_*()` metodlari orqali chaining pattern bilan sozlanadi:
///
/// | Metod | Default qiymat | Tavsif |
/// |-------|---------------|--------|
/// | [`with_timeout()`](Config::with_timeout) | 15 soniya | HTTP so'rov timeout |
/// | [`with_connect_timeout()`](Config::with_connect_timeout) | 2 soniya | TCP/TLS ulanish timeout |
/// | [`with_user_agent()`](Config::with_user_agent) | `myid-client-rust/0.1` | HTTP User-Agent header |
/// | [`with_proxy()`](Config::with_proxy) | `None` | Outbound HTTP/HTTPS proxy |
///
/// # Thread-safety
///
/// `Config` `Send + Sync` traitlarini implement qiladi va
/// xavfsiz tarzda threadlar orasida share qilinishi mumkin.
/// Bu compile-time'da kafolatlanadi.
///
/// # Xavfsizlik
///
/// - `client_secret` [`Debug`] output'da `<redacted>` sifatida ko'rsatiladi
/// - Secret faqat [`Config::client_secret()`] orqali olinadi
/// - Production'da secret'ni environment variable orqali bering, kodni hardcode qilmang
#[derive(Clone)]
pub struct Config {
    /// API bazaviy URL. Trailing slash avtomatik qo'shiladi.
    ///
    /// Misol: `https://myid.example.uz/`
    /// Faqat `http` va `https` scheme qabul qilinadi.
    base_url: Url,

    /// OAuth `client_id` — public identifikator.
    client_id: String,

    /// OAuth `client_secret` — faqat backend muhitida saqlanishi kerak.
    ///
    /// Debug output'da `<redacted>` sifatida ko'rsatiladi.
    client_secret: String,

    /// TCP/TLS ulanish bosqichi uchun connection timeout.
    ///
    /// Default: 2 soniya. `with_connect_timeout()` orqali o'zgartirish mumkin.
    connection_timeout_ms: Duration,

    /// HTTP so'rov uchun timeout.
    ///
    /// Default: 15 soniya. `with_timeout()` orqali o'zgartirish mumkin.
    timeout_ms: Duration,

    /// HTTP `User-Agent` sarlavhasi — observability va diagnostika uchun.
    ///
    /// Default qiymatda heap allokatsiya bo'lmaydi (`Cow::Borrowed`).
    /// Custom qiymat berilsa `Cow::Owned` ga o'tadi.
    user_agent: Cow<'static, str>,

    /// Ixtiyoriy outbound HTTP/HTTPS proxy URL.
    ///
    /// Agar korporativ tarmoqda proxy orqali chiqish kerak bo'lsa ishlatiladi.
    /// Faqat `http` va `https` scheme qabul qilinadi.
    proxy_url: Option<Url>,
}

impl Config {
    /// Yangi `Config` instansini yaratadi.
    ///
    /// 3 ta majburiy parametr talab qilinadi. Qolgan barcha parametrlar
    /// default qiymatlarga ega va `with_*()` metodlari orqali o'zgartirilishi mumkin.
    ///
    /// # Parametrlar
    ///
    /// - `base_url` — MyID API bazaviy URL (masalan: `https://myid.uz`).
    ///   Trailing slash avtomatik qo'shiladi. Faqat `http` va `https` qabul qilinadi.
    /// - `client_id` — OAuth 2.0 client identifikator (public).
    /// - `client_secret` — OAuth 2.0 client secret (**maxfiy**, faqat backend'da saqlang).
    ///
    /// # Xatolar
    ///
    /// [`MyIdError::Config`] qaytaradi agar:
    /// - `base_url` noto'g'ri URL formatida bo'lsa
    /// - URL scheme `http` yoki `https` dan farqli bo'lsa
    ///
    /// [`MyIdError::Validation`] qaytaradi agar:
    /// - `client_id` bo'sh yoki faqat bo'shliqlardan iborat bo'lsa
    /// - `client_secret` bo'sh yoki faqat bo'shliqlardan iborat bo'lsa
    ///
    /// # Misollar
    ///
    /// ```rust
    /// use myid::config::Config;
    /// # use myid::error::MyIdResult;
    ///
    /// # fn main() -> MyIdResult<()> {
    /// // Minimal
    /// let config = Config::new("https://myid.uz", "app_id", "secret")?;
    /// assert_eq!(config.base_url(), "https://myid.uz/");
    ///
    /// // Trailing slash mavjud bo'lsa ham to'g'ri ishlaydi
    /// let config = Config::new("https://myid.uz/", "app_id", "secret")?;
    /// assert_eq!(config.base_url(), "https://myid.uz/");
    ///
    /// // Noto'g'ri URL xato qaytaradi
    /// assert!(Config::new("not-a-url", "id", "secret").is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(
        base_url: impl AsRef<str>,
        client_id: impl Into<String>,
        client_secret: impl Into<String>,
    ) -> MyIdResult<Self> {
        let base_url = Self::parse_and_normalize_url(&base_url)?;
        let client_id = client_id.into();
        let client_secret = client_secret.into();

        if client_id.trim().is_empty() {
            return Err(MyIdError::validation("client_id bo'sh bo'lmasligi kerak"));
        }
        if client_secret.trim().is_empty() {
            return Err(MyIdError::validation(
                "client_secret bo'sh bo'lmasligi kerak",
            ));
        }

        Ok(Self {
            base_url,
            client_id,
            client_secret,
            connection_timeout_ms: Duration::from_millis(DEFAULT_CONNECT_TIMEOUT_MS),
            timeout_ms: Duration::from_millis(DEFAULT_TIMEOUT_MS),
            user_agent: Cow::Borrowed(DEFAULT_USER_AGENT),
            proxy_url: None,
        })
    }

    /// Environment o'zgaruvchilaridan `Config` yaratadi.
    ///
    /// `dotenvy` feature yoqilgan bo'lsa, `.env` fayli avtomatik yuklanadi.
    ///
    /// # Parametrlar
    ///
    /// - `prefix` — env o'zgaruvchilari prefiksi. `None` bo'lsa `MYID_` ishlatiladi.
    ///   Prefiksga `_` avtomatik qo'shiladi (masalan: `"APP"` → `"APP_"`).
    ///
    /// # O'qiladigan env o'zgaruvchilari
    ///
    /// | O'zgaruvchi                  | Turi     | Default               |
    /// |------------------------------|----------|-----------------------|
    /// | `{prefix}BASE_URL`           | Majburiy | —                     |
    /// | `{prefix}CLIENT_ID`          | Majburiy | —                     |
    /// | `{prefix}CLIENT_SECRET`      | Majburiy | —                     |
    /// | `{prefix}CONNECT_TIMEOUT_MS` | u64      | 2000                  |
    /// | `{prefix}TIMEOUT_MS`         | u64      | 15000                 |
    /// | `{prefix}USER_AGENT`         | String   | `myid-client-rust/0.1`|
    /// | `{prefix}PROXY_URL`          | URL      | `None`                |
    ///
    /// # Xatolar
    ///
    /// [`MyIdError::Config`] qaytaradi agar:
    /// - Majburiy o'zgaruvchi topilmasa yoki bo'sh bo'lsa
    /// - URL yoki proxy URL noto'g'ri formatda bo'lsa
    /// - Timeout qiymati `u64` ga parse bo'lmasa yoki `0` bo'lsa
    ///
    /// # Misollar
    ///
    /// ```rust,no_run
    /// use myid::config::Config;
    /// # use myid::error::MyIdResult;
    ///
    /// # fn main() -> MyIdResult<()> {
    /// // Default prefiks (MYID_BASE_URL, MYID_CLIENT_ID, ...)
    /// let config = Config::from_env(None)?;
    ///
    /// // Custom prefiks (APP_BASE_URL, APP_CLIENT_ID, ...)
    /// let config = Config::from_env(Some("APP"))?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_env(prefix: Option<&str>) -> MyIdResult<Self> {
        #[cfg(feature = "dotenvy")]
        {
            let _ = dotenvy::dotenv();
        }

        let p = Self::normalize_prefix(prefix.unwrap_or(DEFAULT_PREFIX));

        let base_url =
            Self::parse_and_normalize_url(&Self::read_required(&format!("{p}BASE_URL"))?)?;
        let client_id = Self::read_required(&format!("{p}CLIENT_ID"))?;
        let client_secret = Self::read_required(&format!("{p}CLIENT_SECRET"))?;

        let connection_timeout_ms = Self::read_u64_or_default(
            &format!("{p}CONNECT_TIMEOUT_MS"),
            DEFAULT_CONNECT_TIMEOUT_MS,
        )?;
        let timeout_ms = Self::read_u64_or_default(&format!("{p}TIMEOUT_MS"), DEFAULT_TIMEOUT_MS)?;

        let user_agent: Cow<'static, str> = match Self::read_optional(&format!("{p}USER_AGENT")) {
            Some(ua) => Cow::Owned(ua),
            None => Cow::Borrowed(DEFAULT_USER_AGENT),
        };

        let proxy_url = Self::read_optional(&format!("{p}PROXY_URL"))
            .map(|raw| Self::parse_url(&raw))
            .transpose()?;

        Ok(Self {
            base_url,
            client_id,
            client_secret,
            connection_timeout_ms: Duration::from_millis(connection_timeout_ms),
            timeout_ms: Duration::from_millis(timeout_ms),
            user_agent,
            proxy_url,
        })
    }

    // --- Builder methods (with_*) ---

    /// TCP/TLS ulanish timeout'ini o'zgartiradi.
    ///
    /// Bu faqat ulanish bosqichi (TCP handshake + TLS negotiation) uchun.
    /// Server javob vaqti uchun [`Config::with_timeout()`] ishlatiladi.
    ///
    /// Default: **2 soniya**.
    ///
    /// # Misollar
    ///
    /// ```rust
    /// use std::time::Duration;
    /// use myid::config::Config;
    /// # use myid::error::MyIdResult;
    ///
    /// # fn main() -> MyIdResult<()> {
    /// let config = Config::new("https://myid.uz", "id", "secret")?
    ///     .with_connect_timeout(Duration::from_secs(10));
    ///
    /// assert_eq!(config.connection_timeout(), Duration::from_secs(10));
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    #[inline]
    pub fn with_connect_timeout(mut self, timeout: Duration) -> Self {
        self.connection_timeout_ms = timeout;
        self
    }

    /// HTTP so'rov timeout'ini o'zgartiradi.
    ///
    /// Bu butun so'rov davomiyligi uchun — ulanish, yuborish va javob qabul qilish.
    /// Agar server shu vaqt ichida javob bermasa, so'rov bekor qilinadi.
    ///
    /// Default: **15 soniya**.
    ///
    /// # Misollar
    ///
    /// ```rust
    /// use std::time::Duration;
    /// use myid::config::Config;
    /// # use myid::error::MyIdResult;
    ///
    /// # fn main() -> MyIdResult<()> {
    /// let config = Config::new("https://myid.uz", "id", "secret")?
    ///     .with_timeout(Duration::from_secs(60));
    ///
    /// assert_eq!(config.timeout(), Duration::from_secs(60));
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    #[inline]
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout_ms = timeout;
        self
    }

    /// HTTP `User-Agent` sarlavhasini o'zgartiradi.
    ///
    /// `User-Agent` header har bir HTTP so'rovda yuboriladi.
    /// Server tomonida so'rovlarni identifikatsiya qilish va
    /// monitoring uchun foydali.
    ///
    /// Default: `myid-client-rust/0.1`.
    ///
    /// # Misollar
    ///
    /// ```rust
    /// use myid::config::Config;
    /// # use myid::error::MyIdResult;
    ///
    /// # fn main() -> MyIdResult<()> {
    /// let config = Config::new("https://myid.uz", "id", "secret")?
    ///     .with_user_agent("my-backend/2.0");
    ///
    /// assert_eq!(config.user_agent(), "my-backend/2.0");
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    #[inline]
    pub fn with_user_agent(mut self, agent: impl Into<String>) -> Self {
        self.user_agent = Cow::Owned(agent.into());
        self
    }

    /// Outbound HTTP/HTTPS proxy URL'ni sozlaydi.
    ///
    /// Korporativ tarmoqlarda internet chiqish faqat proxy orqali
    /// bo'lishi mumkin. Bu holda shu metod orqali proxy URL beriladi.
    ///
    /// Faqat `http` va `https` scheme qabul qilinadi.
    ///
    /// # Xatolar
    ///
    /// [`MyIdError::Config`] qaytaradi agar:
    /// - URL noto'g'ri formatda bo'lsa
    /// - Scheme `http` yoki `https` dan farqli bo'lsa
    ///
    /// # Misollar
    ///
    /// ```rust
    /// use myid::config::Config;
    /// # use myid::error::MyIdResult;
    ///
    /// # fn main() -> MyIdResult<()> {
    /// let config = Config::new("https://myid.uz", "id", "secret")?
    ///     .with_proxy("http://proxy.corp.local:8080")?;
    ///
    /// assert!(config.proxy_url().is_some());
    ///
    /// // FTP proxy qabul qilinmaydi
    /// let result = Config::new("https://myid.uz", "id", "secret")?
    ///     .with_proxy("ftp://proxy.local");
    /// assert!(result.is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_proxy(mut self, url: impl AsRef<str>) -> MyIdResult<Self> {
        self.proxy_url = Some(Self::parse_url(&url)?);
        Ok(self)
    }

    // --- Getter methods ---

    /// API bazaviy URL'ni `&str` sifatida qaytaradi.
    ///
    /// Qaytariladigan URL har doim trailing slash (`/`) bilan tugaydi.
    ///
    /// # Misollar
    ///
    /// ```rust
    /// # use myid::config::Config;
    /// # use myid::error::MyIdResult;
    /// # fn main() -> MyIdResult<()> {
    /// let config = Config::new("https://myid.uz", "id", "secret")?;
    /// assert_eq!(config.base_url(), "https://myid.uz/");
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn base_url(&self) -> &str {
        self.base_url.as_str()
    }

    /// OAuth `client_id` qiymatini qaytaradi.
    ///
    /// Bu public identifikator — logga chiqarish xavfsiz.
    #[inline]
    pub fn client_id(&self) -> &str {
        &self.client_id
    }

    /// OAuth `client_secret` qiymatini qaytaradi.
    ///
    /// ⚠️ **Ogohlantirish:** bu qiymat maxfiy. Logga, stdout'ga yoki
    /// tashqi tizimlarga **chiqarmang**. [`Debug`] output'da avtomatik
    /// `<redacted>` sifatida ko'rsatiladi.
    #[inline]
    pub fn client_secret(&self) -> &str {
        &self.client_secret
    }

    /// TCP/TLS ulanish timeout qiymatini qaytaradi.
    ///
    /// Default: 2 soniya. [`Config::with_connect_timeout()`] orqali o'zgartiriladi.
    #[inline]
    pub fn connection_timeout(&self) -> Duration {
        self.connection_timeout_ms
    }

    /// HTTP so'rov timeout qiymatini qaytaradi.
    ///
    /// Default: 15 soniya. [`Config::with_timeout()`] orqali o'zgartiriladi.
    #[inline]
    pub fn timeout(&self) -> Duration {
        self.timeout_ms
    }

    /// HTTP `User-Agent` header qiymatini qaytaradi.
    ///
    /// Default: `myid-client-rust/0.1`.
    #[inline]
    pub fn user_agent(&self) -> &str {
        self.user_agent.as_ref()
    }

    /// Proxy URL'ni `&str` sifatida qaytaradi (agar o'rnatilgan bo'lsa).
    ///
    /// Proxy sozlanmagan bo'lsa `None` qaytaradi.
    ///
    /// # Misollar
    ///
    /// ```rust
    /// # use myid::config::Config;
    /// # use myid::error::MyIdResult;
    /// # fn main() -> MyIdResult<()> {
    /// // Proxy yo'q
    /// let config = Config::new("https://myid.uz", "id", "secret")?;
    /// assert_eq!(config.proxy_url(), None);
    ///
    /// // Proxy bor
    /// let config = Config::new("https://myid.uz", "id", "secret")?
    ///     .with_proxy("http://proxy:8080")?;
    /// assert!(config.proxy_url().is_some());
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn proxy_url(&self) -> Option<&str> {
        self.proxy_url.as_ref().map(Url::as_str)
    }

    // --- Crate-internal methods ---

    /// API bazaviy URL'ni [`Url`] sifatida qaytaradi.
    ///
    /// Crate ichida endpoint yaratish uchun ishlatiladi:
    ///
    /// ```rust,ignore
    /// let endpoint = config.base_url_parsed().join("api/v1/verify")?;
    /// ```
    #[inline]
    pub(crate) fn base_url_parsed(&self) -> &Url {
        &self.base_url
    }

    // --- Private methods ---

    /// URL stringni parse, validate va normalize qiladi.
    ///
    /// Faqat `http` va `https` scheme qabul qiladi.
    /// Trailing slash avtomatik qo'shiladi.
    fn parse_and_normalize_url(raw: impl AsRef<str>) -> MyIdResult<Url> {
        let mut url = Self::parse_url(&raw)?;

        if !url.path().ends_with('/') {
            url.set_path(&format!("{}/", url.path()));
        }
        Ok(url)
    }

    /// URL stringni parse va validate qiladi.
    ///
    /// Faqat `http` va `https` scheme qabul qiladi.
    /// Boshqa schemalar (ftp, ws, va h.k.) rad etiladi.
    fn parse_url(raw: impl AsRef<str>) -> MyIdResult<Url> {
        let url = Url::parse(raw.as_ref())
            .map_err(|e| MyIdError::config(format!("invalid URL `{}`: {e}", raw.as_ref())))?;

        match url.scheme() {
            "http" | "https" => Ok(url),
            other => Err(MyIdError::config(format!(
                "only http/https are accepted, given: {other}"
            ))),
        }
    }

    /// Prefiksni normalizatsiya qiladi — oxirida `_` bo'lishini kafolatlaydi.
    ///
    /// - Bo'sh string → `MYID_` (default)
    /// - `"APP"` → `"APP_"`
    /// - `"APP_"` → `"APP_"` (o'zgarishsiz)
    fn normalize_prefix(prefix: &str) -> String {
        let s = prefix.trim();
        if s.is_empty() {
            return DEFAULT_PREFIX.to_string();
        }
        if s.ends_with('_') {
            s.to_string()
        } else {
            format!("{s}_")
        }
    }

    /// Majburiy env o'zgaruvchisini o'qiydi.
    ///
    /// Topilmasa yoki bo'sh bo'lsa xato qaytaradi. Qiymat `trim()` qilinadi.
    fn read_required(key: &str) -> MyIdResult<String> {
        let value =
            env::var(key).map_err(|_| MyIdError::config(format!("missing env var: {key}")))?;

        let trimmed = value.trim();
        if trimmed.is_empty() {
            return Err(MyIdError::config(format!("empty env var: {key}")));
        }
        Ok(trimmed.to_owned())
    }

    /// Ixtiyoriy env o'zgaruvchisini o'qiydi.
    ///
    /// Topilmasa yoki bo'sh bo'lsa `None` qaytaradi.
    fn read_optional(key: &str) -> Option<String> {
        env::var(key).ok().and_then(|v| {
            let trimmed = v.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some(trimmed.to_owned())
            }
        })
    }

    /// Env o'zgaruvchisidan `u64` o'qiydi, topilmasa default ishlatadi.
    ///
    /// Qiymat `0` bo'lsa xato qaytaradi (timeout uchun mantiqsiz).
    fn read_u64_or_default(key: &str, default: u64) -> MyIdResult<u64> {
        match Self::read_optional(key) {
            None => Ok(default),
            Some(v) => {
                let parsed: u64 = v
                    .parse()
                    .map_err(|_| MyIdError::config(format!("invalid u64: {key}={v}")))?;

                if parsed == 0 {
                    return Err(MyIdError::config(format!("{key} must be > 0")));
                }
                Ok(parsed)
            }
        }
    }
}

/// [`Debug`] implementatsiyasi `client_secret` ni yashiradi.
///
/// Log yoki panic output'da credential'lar sizib chiqishining oldini oladi.
/// `client_id` ochiq ko'rsatiladi — bu public identifikator.
///
/// # Misol
///
/// ```rust
/// # use myid::config::Config;
/// # use myid::error::MyIdResult;
/// # fn main() -> MyIdResult<()> {
/// let config = Config::new("https://myid.uz", "my_app", "super_secret")?;
/// let debug = format!("{:?}", config);
///
/// // Secret ko'rinmaydi
/// assert!(debug.contains("<redacted>"));
/// assert!(!debug.contains("super_secret"));
///
/// // Client ID ko'rinadi
/// assert!(debug.contains("my_app"));
/// # Ok(())
/// # }
/// ```
impl fmt::Debug for Config {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Config")
            .field("base_url", &self.base_url.as_str())
            .field("client_id", &self.client_id.as_str())
            .field("client_secret", &"<redacted>")
            .field("connection_timeout_ms", &self.connection_timeout_ms)
            .field("timeout_ms", &self.timeout_ms)
            .field("user_agent", &self.user_agent.as_ref())
            .field("proxy_url", &self.proxy_url.as_ref().map(|p| p.as_str()))
            .finish()
    }
}