ignitia 0.2.4

A blazing fast, lightweight web framework for Rust that ignites your development journey
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
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
//! # HTTP Response Generation Module
//!
//! This module provides comprehensive HTTP response generation capabilities for the Ignitia web framework.
//! It includes response building, content type handling, status code management, and error response generation
//! with efficient serialization and flexible customization options.
//!
//! ## Features
//!
//! - **Multiple Response Formats**: JSON, HTML, text, and binary response generation
//! - **Status Code Management**: Easy status code setting with validation
//! - **Header Management**: Flexible header manipulation and content type handling
//! - **Error Response Generation**: Automatic error-to-response conversion with structured formats
//! - **Builder Pattern Support**: Fluent response building with method chaining
//! - **Performance Optimized**: Efficient serialization and memory usage
//!
//! ## Response Types
//!
//! ### JSON Responses
//! - Automatic serialization with proper content-type headers
//! - Support for any type implementing `Serialize`
//! - Comprehensive error handling for serialization failures
//!
//! ### HTML Responses
//! - Proper content-type headers with charset specification
//! - Template integration support
//! - XSS protection considerations
//!
//! ### Text Responses
//! - UTF-8 encoded plain text with proper headers
//! - Support for various text formats
//!
//! ### Binary Responses
//! - Efficient handling of binary data
//! - Flexible content-type specification
//! - Support for file downloads and streaming
//!
//! ## Usage Examples
//!
//! ### Basic Response Creation
//! ```
//! use ignitia::{Response, Result};
//! use http::StatusCode;
//!
//! // Simple text response
//! async fn hello_handler() -> Result<Response> {
//!     Ok(Response::text("Hello, World!"))
//! }
//!
//! // JSON response
//! async fn json_handler() -> Result<Response> {
//!     let data = serde_json::json!({
//!         "message": "Hello, World!",
//!         "timestamp": chrono::Utc::now()
//!     });
//!     Response::json(data)
//! }
//!
//! // HTML response
//! async fn html_handler() -> Result<Response> {
//!     let html = r#"
//!         <!DOCTYPE html>
//!         <html>
//!         <head><title>Hello</title></head>
//!         <body><h1>Hello, World!</h1></body>
//!         </html>
//!     "#;
//!     Ok(Response::html(html))
//! }
//! ```
//!
//! ### Custom Status Codes
//! ```
//! use ignitia::Response;
//! use http::StatusCode;
//!
//! async fn custom_status_handler() -> ignitia::Result<Response> {
//!     Ok(Response::text("Created successfully")
//!         .with_status(StatusCode::CREATED))
//! }
//!
//! async fn not_found_handler() -> ignitia::Result<Response> {
//!     Ok(Response::text("Resource not found")
//!         .with_status_code(404))
//! }
//! ```
//!
//! ### Working with Headers
//! ```
//! use ignitia::Response;
//! use http::{HeaderMap, HeaderName, HeaderValue};
//!
//! async fn custom_headers_handler() -> ignitia::Result<Response> {
//!     let mut response = Response::text("Custom headers example");
//!
//!     // Add custom headers
//!     response.headers.insert(
//!         HeaderName::from_static("x-custom-header"),
//!         HeaderValue::from_static("custom-value")
//!     );
//!
//!     response.headers.insert(
//!         HeaderName::from_static("cache-control"),
//!         HeaderValue::from_static("no-cache, no-store, must-revalidate")
//!     );
//!
//!     Ok(response)
//! }
//! ```
//!
//! ## Advanced Usage
//!
//! ### API Response Patterns
//! ```
//! use ignitia::{Response, Result};
//! use serde::{Deserialize, Serialize};
//! use http::StatusCode;
//!
//! #[derive(Serialize)]
//! struct ApiResponse<T> {
//!     success: bool,
//!     data: Option<T>,
//!     message: String,
//!     timestamp: String,
//! }
//!
//! #[derive(Serialize)]
//! struct User {
//!     id: u32,
//!     name: String,
//!     email: String,
//! }
//!
//! async fn get_user_handler() -> Result<Response> {
//!     let user = User {
//!         id: 1,
//!         name: "Alice".to_string(),
//!         email: "alice@example.com".to_string(),
//!     };
//!
//!     let api_response = ApiResponse {
//!         success: true,
//!         data: Some(user),
//!         message: "User retrieved successfully".to_string(),
//!         timestamp: chrono::Utc::now().to_rfc3339(),
//!     };
//!
//!     Response::json(api_response)
//! }
//!
//! async fn user_not_found_handler() -> Result<Response> {
//!     let api_response = ApiResponse::<()> {
//!         success: false,
//!         data: None,
//!         message: "User not found".to_string(),
//!         timestamp: chrono::Utc::now().to_rfc3339(),
//!     };
//!
//!     let mut response = Response::json(api_response)?;
//!     response.status = StatusCode::NOT_FOUND;
//!     Ok(response)
//! }
//! ```
//!
//! ### File Download Responses
//! ```
//! use ignitia::Response;
//! use bytes::Bytes;
//! use http::{HeaderName, HeaderValue};
//!
//! async fn download_handler() -> ignitia::Result<Response> {
//!     // Simulate file content
//!     let file_content = b"Hello, this is a downloadable file!";
//!     let filename = "example.txt";
//!
//!     let mut response = Response::new(http::StatusCode::OK);
//!     response.body = Bytes::from(&file_content[..]);
//!
//!     // Set appropriate headers for file download
//!     response.headers.insert(
//!         HeaderName::from_static("content-type"),
//!         HeaderValue::from_static("application/octet-stream")
//!     );
//!
//!     response.headers.insert(
//!         HeaderName::from_static("content-disposition"),
//!         HeaderValue::from_str(&format!("attachment; filename=\"{}\"", filename))
//!             .map_err(|_| ignitia::Error::Internal("Invalid filename".into()))?
//!     );
//!
//!     response.headers.insert(
//!         HeaderName::from_static("content-length"),
//!         HeaderValue::from_str(&file_content.len().to_string())
//!             .map_err(|_| ignitia::Error::Internal("Invalid content length".into()))?
//!     );
//!
//!     Ok(response)
//! }
//! ```
//!
//! ### Streaming Responses
//! ```
//! use ignitia::Response;
//! use bytes::Bytes;
//! use http::{HeaderName, HeaderValue};
//!
//! async fn streaming_handler() -> ignitia::Result<Response> {
//!     // Server-Sent Events example
//!     let event_data = "data: Hello from server!\n\n";
//!
//!     let mut response = Response::new(http::StatusCode::OK);
//!     response.body = Bytes::from(event_data);
//!
//!     response.headers.insert(
//!         HeaderName::from_static("content-type"),
//!         HeaderValue::from_static("text/event-stream")
//!     );
//!
//!     response.headers.insert(
//!         HeaderName::from_static("cache-control"),
//!         HeaderValue::from_static("no-cache")
//!     );
//!
//!     response.headers.insert(
//!         HeaderName::from_static("connection"),
//!         HeaderValue::from_static("keep-alive")
//!     );
//!
//!     Ok(response)
//! }
//! ```
//!
//! ## Error Response Handling
//!
//! ### Automatic Error Conversion
//! ```
//! use ignitia::{Response, Error, Result};
//! use http::StatusCode;
//!
//! async fn error_example_handler() -> Result<Response> {
//!     // This will automatically be converted to an error response
//!     Err(Error::NotFound("User not found".to_string()))
//! }
//!
//! // The framework automatically converts errors to responses:
//! // {
//! //   "error": "Not Found",
//! //   "message": "User not found",
//! //   "status": 404,
//! //   "error_type": "not_found",
//! //   "timestamp": "2023-01-01T12:00:00Z"
//! // }
//! ```
//!
//! ### Custom Error Responses
//! ```
//! use ignitia::{Response, Error, Result};
//! use serde_json::json;
//!
//! async fn custom_error_handler() -> Result<Response> {
//!     let error_messages = vec![
//!         "Name is required".to_string(),
//!         "Email format is invalid".to_string(),
//!     ];
//!
//!     Response::validation_error(error_messages)
//! }
//!
//! async fn api_error_handler() -> Result<Response> {
//!     let error_response = json!({
//!         "error": {
//!             "code": "RATE_LIMITED",
//!             "message": "Too many requests",
//!             "retry_after": 60
//!         }
//!     });
//!
//!     let mut response = Response::json(error_response)?;
//!     response.status = http::StatusCode::TOO_MANY_REQUESTS;
//!     Ok(response)
//! }
//! ```
//!
//! ## Performance Considerations
//!
//! ### Memory Efficiency
//! - Uses `bytes::Bytes` for zero-copy operations
//! - Efficient serialization with pre-allocated buffers
//! - Minimal header allocation overhead
//!
//! ### Serialization Performance
//! ```
//! use ignitia::Response;
//! use serde::Serialize;
//!
//! #[derive(Serialize)]
//! struct LargeData {
//!     items: Vec<String>,
//! }
//!
//! async fn optimized_json_handler() -> ignitia::Result<Response> {
//!     let data = LargeData {
//!         items: (0..1000).map(|i| format!("Item {}", i)).collect(),
//!     };
//!
//!     // Efficient JSON serialization with error handling
//!     match Response::json(data) {
//!         Ok(response) => Ok(response),
//!         Err(e) => {
//!             tracing::error!("JSON serialization failed: {}", e);
//!             Ok(Response::text("Internal server error")
//!                 .with_status(http::StatusCode::INTERNAL_SERVER_ERROR))
//!         }
//!     }
//! }
//! ```
//!
//! ## Security Considerations
//!
//! ### Content Type Security
//! - Always set appropriate content-type headers
//! - Validate content before setting as HTML
//! - Use proper encoding for text responses
//!
//! ### XSS Prevention
//! ```
//! use ignitia::Response;
//!
//! async fn safe_html_handler(user_input: &str) -> ignitia::Result<Response> {
//!     // Escape user input to prevent XSS
//!     let escaped_input = html_escape::encode_text(user_input);
//!
//!     let safe_html = format!(
//!         r#"<!DOCTYPE html>
//!         <html>
//!         <head><title>Safe Output</title></head>
//!         <body><h1>Hello, {}</h1></body>
//!         </html>"#,
//!         escaped_input
//!     );
//!
//!     Ok(Response::html(safe_html))
//! }
//! ```
//!
//! ### Security Headers
//! ```
//! use ignitia::Response;
//! use http::{HeaderName, HeaderValue};
//!
//! async fn secure_response_handler() -> ignitia::Result<Response> {
//!     let mut response = Response::html("<h1>Secure Page</h1>");
//!
//!     // Add security headers
//!     response.headers.insert(
//!         HeaderName::from_static("x-content-type-options"),
//!         HeaderValue::from_static("nosniff")
//!     );
//!
//!     response.headers.insert(
//!         HeaderName::from_static("x-frame-options"),
//!         HeaderValue::from_static("DENY")
//!     );
//!
//!     response.headers.insert(
//!         HeaderName::from_static("x-xss-protection"),
//!         HeaderValue::from_static("1; mode=block")
//!     );
//!
//!     response.headers.insert(
//!         HeaderName::from_static("content-security-policy"),
//!         HeaderValue::from_static("default-src 'self'")
//!     );
//!
//!     Ok(response)
//! }
//! ```
//!
//! ## Testing Response Generation
//!
//! ### Unit Testing
//! ```
//! #[cfg(test)]
//! mod tests {
//!     use super::*;
//!     use http::StatusCode;
//!
//!     #[tokio::test]
//!     async fn test_text_response() {
//!         let response = Response::text("Hello, World!");
//!
//!         assert_eq!(response.status, StatusCode::OK);
//!         assert_eq!(
//!             response.headers.get("content-type").unwrap(),
//!             "text/plain; charset=utf-8"
//!         );
//!         assert_eq!(response.body, "Hello, World!");
//!     }
//!
//!     #[tokio::test]
//!     async fn test_json_response() {
//!         let data = serde_json::json!({"message": "test"});
//!         let response = Response::json(data).unwrap();
//!
//!         assert_eq!(response.status, StatusCode::OK);
//!         assert_eq!(
//!             response.headers.get("content-type").unwrap(),
//!             "application/json"
//!         );
//!     }
//!
//!     #[tokio::test]
//!     async fn test_error_conversion() {
//!         let error = ignitia::Error::NotFound("test".to_string());
//!         let response = Response::from(error);
//!
//!         assert_eq!(response.status, StatusCode::NOT_FOUND);
//!     }
//! }
//! ```

pub mod builder;
pub mod status;

pub mod into_response;

// Re-export IntoResponse
pub use into_response::{Html, IntoResponse};

use bytes::Bytes;
use http::{header, HeaderMap, HeaderName, HeaderValue, StatusCode};
use serde::Serialize;

/// HTTP response representation containing status, headers, and body.
///
/// The `Response` struct encapsulates all data needed to send an HTTP response,
/// including the status code, headers, and body content. It provides convenient
/// methods for creating responses with different content types and formats.
///
/// # Structure
/// - **status**: HTTP status code (200, 404, 500, etc.)
/// - **headers**: HTTP headers as a HeaderMap
/// - **body**: Response body as bytes
///
/// # Examples
///
/// ## Basic Response Creation
/// ```
/// use ignitia::Response;
/// use http::StatusCode;
///
/// // Create a simple text response
/// let response = Response::text("Hello, World!");
/// assert_eq!(response.status, StatusCode::OK);
///
/// // Create a response with custom status
/// let response = Response::new(StatusCode::CREATED);
/// ```
///
/// ## JSON Responses
/// ```
/// use ignitia::Response;
/// use serde_json::json;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let data = json!({
///     "message": "Success",
///     "data": {
///         "id": 123,
///         "name": "Example"
///     }
/// });
///
/// let response = Response::json(data)?;
/// # Ok(())
/// # }
/// ```
///
/// ## HTML Responses
/// ```
/// use ignitia::Response;
///
/// let html = r#"
/// <!DOCTYPE html>
/// <html>
/// <head><title>Hello</title></head>
/// <body><h1>Hello, World!</h1></body>
/// </html>
/// "#;
///
/// let response = Response::html(html);
/// ```
#[derive(Debug, Clone)]
pub struct Response {
    /// HTTP status code
    pub status: StatusCode,
    /// HTTP response headers
    pub headers: HeaderMap,
    /// Response body as bytes
    pub body: Bytes,
    /// Cache control information
    pub cache_control: Option<CacheControl>, // Add this field
}

/// HTTP cache control configuration for optimizing response caching.
///
/// The `CacheControl` struct encapsulates caching metadata used to optimize
/// HTTP response delivery through strategic cache management. It provides
/// fine-grained control over cache behavior including cache duration and
/// cache key generation for efficient content delivery.
///
/// # Purpose
///
/// This struct enables:
/// - **Cache Duration Control**: Setting appropriate cache lifetimes via `max_age`
/// - **Cache Key Management**: Generating unique identifiers for cached content
/// - **Performance Optimization**: Reducing server load through intelligent caching
/// - **CDN Integration**: Supporting Content Delivery Network caching strategies
///
/// # Cache Strategy
///
/// The cache control system implements a dual-approach strategy:
/// 1. **Time-based Expiration**: Uses `max_age` for cache lifetime management
/// 2. **Content-based Invalidation**: Uses `key` for cache versioning and invalidation
///
/// # Integration with Response
///
/// When attached to a `Response`, the `CacheControl` struct automatically:
/// - Sets appropriate HTTP cache headers (`Cache-Control`, `ETag`, etc.)
/// - Generates cache keys for storage systems
/// - Enables conditional requests (304 Not Modified responses)
/// - Supports cache invalidation strategies
///
/// # Examples
///
/// ## Basic Cache Control
/// ```
/// use ignitia::{Response, CacheControl};
///
/// let cache_control = CacheControl {
///     max_age: 3600, // 1 hour
///     key: "user_profile_123".to_string(),
/// };
///
/// let response = Response::json(user_data)?
///     .with_cache_control(cache_control);
/// ```
///
/// ## Static Asset Caching
/// ```
/// // Long-term caching for static assets
/// let static_cache = CacheControl {
///     max_age: 31536000, // 1 year
///     key: format!("static_{}_{}", filename, version_hash),
/// };
/// ```
///
/// ## API Response Caching
/// ```
/// // Short-term caching for API responses
/// let api_cache = CacheControl {
///     max_age: 300, // 5 minutes
///     key: format!("api_{}_{}_{}", endpoint, user_id, timestamp),
/// };
/// ```
///
/// ## Dynamic Content Caching
/// ```
/// // User-specific content with medium cache duration
/// let user_cache = CacheControl {
///     max_age: 1800, // 30 minutes
///     key: format!("content_{}_{}", content_id, last_modified),
/// };
/// ```
#[derive(Debug, Clone)]
pub struct CacheControl {
    /// Maximum age for cached content in seconds.
    ///
    /// This field determines how long the content should be considered fresh
    /// by browsers, CDNs, and intermediate caches. The value directly maps
    /// to the HTTP `Cache-Control: max-age=` directive.
    ///
    /// # Common Values
    /// - **0**: No caching (always revalidate)
    /// - **300**: 5 minutes (dynamic API responses)
    /// - **3600**: 1 hour (semi-static content)
    /// - **86400**: 24 hours (daily updated content)
    /// - **31536000**: 1 year (static assets with versioning)
    ///
    /// # Performance Considerations
    /// - Longer cache times reduce server load but may serve stale content
    /// - Shorter cache times ensure freshness but increase server requests
    /// - Consider content update frequency when setting values
    ///
    /// # Examples
    /// ```
    /// // No caching for sensitive data
    /// let sensitive = CacheControl { max_age: 0, key: "...".to_string() };
    ///
    /// // Medium caching for API responses
    /// let api = CacheControl { max_age: 600, key: "...".to_string() };
    ///
    /// // Long caching for static assets
    /// let static_content = CacheControl { max_age: 2592000, key: "...".to_string() };
    /// ```
    pub max_age: u64,

    /// Unique identifier for cache entry management and invalidation.
    ///
    /// The cache key serves multiple purposes in the caching infrastructure:
    /// - **Uniqueness**: Ensures different content versions are cached separately
    /// - **Invalidation**: Enables targeted cache clearing when content changes
    /// - **Versioning**: Supports content versioning through key changes
    /// - **Debugging**: Provides identifiable cache entries for troubleshooting
    ///
    /// # Key Generation Strategies
    ///
    /// ## Content-Based Keys
    /// Include content identifiers that change when content changes:
    /// ```
    /// let key = format!("article_{}_{}", article_id, last_modified_timestamp);
    /// ```
    ///
    /// ## User-Specific Keys
    /// Include user context for personalized content:
    /// ```
    /// let key = format!("dashboard_{}_{}_{}", user_id, role, preferences_hash);
    /// ```
    ///
    /// ## Version-Based Keys
    /// Include application or content version for cache busting:
    /// ```
    /// let key = format!("api_response_{}_v{}", endpoint, api_version);
    /// ```
    ///
    /// ## Hierarchical Keys
    /// Use hierarchical structure for organized cache management:
    /// ```
    /// let key = format!("app:{}:user:{}:page:{}", app_version, user_id, page_id);
    /// ```
    ///
    /// # Best Practices
    /// - Include all relevant context that affects content
    /// - Use consistent naming conventions across the application
    /// - Include version or timestamp information for automatic invalidation
    /// - Keep keys reasonably short while maintaining uniqueness
    /// - Avoid sensitive information in cache keys
    ///
    /// # Performance Notes
    /// - Shorter keys reduce memory overhead in cache systems
    /// - Consistent key patterns improve cache hit rates
    /// - Include enough context to avoid cache collisions
    /// - Consider key distribution for cache sharding strategies
    pub key: String,
}

impl Response {
    /// Creates a new Response with the specified status code.
    ///
    /// This is the basic constructor for Response instances. It creates a response
    /// with the given status code, empty headers, and an empty body.
    ///
    /// # Parameters
    /// - `status`: The HTTP status code for the response
    ///
    /// # Returns
    /// A new Response instance
    ///
    /// # Examples
    /// ```
    /// use ignitia::Response;
    /// use http::StatusCode;
    ///
    /// let response = Response::new(StatusCode::OK);
    /// assert_eq!(response.status, StatusCode::OK);
    /// assert!(response.body.is_empty());
    ///
    /// let error_response = Response::new(StatusCode::INTERNAL_SERVER_ERROR);
    /// assert_eq!(error_response.status, StatusCode::INTERNAL_SERVER_ERROR);
    /// ```
    #[inline]
    pub fn new(status: StatusCode) -> Self {
        Self {
            status,
            headers: HeaderMap::new(),
            body: Bytes::new(),
            cache_control: None,
        }
    }

    /// Sets the status code of the response (builder pattern).
    ///
    /// This method consumes the response and returns it with the new status code,
    /// enabling fluent method chaining.
    ///
    /// # Parameters
    /// - `status`: The new status code to set
    ///
    /// # Returns
    /// The response with the updated status code
    ///
    /// # Examples
    /// ```
    /// use ignitia::Response;
    /// use http::StatusCode;
    ///
    /// let response = Response::text("Created successfully")
    ///     .with_status(StatusCode::CREATED);
    /// assert_eq!(response.status, StatusCode::CREATED);
    /// ```
    #[inline]
    pub fn with_status(mut self, status: StatusCode) -> Self {
        self.status = status;
        self
    }

    /// Sets the status code using a numeric value (builder pattern).
    ///
    /// This is a convenience method that accepts a u16 status code and converts
    /// it to a StatusCode. Invalid status codes are ignored.
    ///
    /// # Parameters
    /// - `status_code`: The numeric status code (e.g., 200, 404, 500)
    ///
    /// # Returns
    /// The response with the updated status code (if valid)
    ///
    /// # Examples
    /// ```
    /// use ignitia::Response;
    ///
    /// let response = Response::text("Not Found")
    ///     .with_status_code(404);
    /// assert_eq!(response.status.as_u16(), 404);
    ///
    /// // Invalid status codes are ignored
    /// let response = Response::text("Test")
    ///     .with_status_code(9999); // Invalid, ignored
    /// ```
    #[inline]
    pub fn with_status_code(mut self, status_code: u16) -> Self {
        if let Ok(status) = StatusCode::from_u16(status_code) {
            self.status = status;
        }
        self
    }

    /// Sets the response body (builder pattern).
    ///
    /// This method accepts any type that can be converted to `Bytes` and sets
    /// it as the response body.
    ///
    /// # Parameters
    /// - `body`: The body content (String, &str, Vec<u8>, Bytes, etc.)
    ///
    /// # Returns
    /// The response with the updated body
    ///
    /// # Examples
    /// ```
    /// use ignitia::Response;
    /// use bytes::Bytes;
    ///
    /// // From string
    /// let response = Response::new(http::StatusCode::OK)
    ///     .with_body("Hello, World!");
    ///
    /// // From bytes
    /// let data = Bytes::from("Binary data");
    /// let response = Response::new(http::StatusCode::OK)
    ///     .with_body(data);
    /// ```
    #[inline]
    pub fn with_body(mut self, body: impl Into<Bytes>) -> Self {
        self.body = body.into();
        self
    }

    /// Returns a shared reference to the response body.
    ///
    /// This method returns a shared reference to the response body, allowing
    /// multiple parts of the application to access the body without cloning it.
    ///
    /// # Returns
    /// A shared reference to the response body
    ///
    /// # Examples
    /// ```
    /// use ignitia::Response;
    /// use bytes::Bytes;
    ///
    /// let response = Response::new(http::StatusCode::OK)
    ///     .with_body("Hello, World!");
    ///
    /// let body = response.body_shared();
    /// assert_eq!(body.as_ref(), b"Hello, World!");
    /// ```
    #[inline]
    pub fn body_shared(&self) -> &Bytes {
        &self.body
    }

    /// Creates a successful response (200 OK).
    ///
    /// This is a convenience method for creating responses with a 200 OK status.
    ///
    /// # Returns
    /// A new response with status 200 OK
    ///
    /// # Examples
    /// ```
    /// use ignitia::Response;
    /// use http::StatusCode;
    ///
    /// let response = Response::ok();
    /// assert_eq!(response.status, StatusCode::OK);
    /// ```
    #[inline]
    pub fn ok() -> Self {
        Self::new(StatusCode::OK)
    }

    /// Creates a not found response (404 Not Found).
    ///
    /// This is a convenience method for creating 404 responses.
    ///
    /// # Returns
    /// A new response with status 404 Not Found
    ///
    /// # Examples
    /// ```
    /// use ignitia::Response;
    /// use http::StatusCode;
    ///
    /// let response = Response::not_found();
    /// assert_eq!(response.status, StatusCode::NOT_FOUND);
    /// ```
    #[inline]
    pub fn not_found() -> Self {
        Self::new(StatusCode::NOT_FOUND)
    }

    /// Creates an internal server error response (500 Internal Server Error).
    ///
    /// This is a convenience method for creating 500 error responses.
    ///
    /// # Returns
    /// A new response with status 500 Internal Server Error
    ///
    /// # Examples
    /// ```
    /// use ignitia::Response;
    /// use http::StatusCode;
    ///
    /// let response = Response::internal_error();
    /// assert_eq!(response.status, StatusCode::INTERNAL_SERVER_ERROR);
    /// ```
    #[inline]
    pub fn internal_error() -> Self {
        Self::new(StatusCode::INTERNAL_SERVER_ERROR)
    }

    /// Creates a JSON response with automatic serialization.
    ///
    /// This method serializes the provided data to JSON and creates a response
    /// with the appropriate content-type header. It returns a Result because
    /// serialization can fail.
    ///
    /// # Type Parameters
    /// - `T`: The type to serialize (must implement `Serialize`)
    ///
    /// # Parameters
    /// - `data`: The data to serialize as JSON
    ///
    /// # Returns
    /// - `Ok(Response)`: Successfully created JSON response
    /// - `Err(Error)`: JSON serialization error
    ///
    /// # Examples
    /// ```
    /// use ignitia::Response;
    /// use serde::Serialize;
    /// use serde_json::json;
    ///
    /// #[derive(Serialize)]
    /// struct ApiResponse {
    ///     success: bool,
    ///     message: String,
    /// }
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // With custom struct
    /// let data = ApiResponse {
    ///     success: true,
    ///     message: "Operation completed".to_string(),
    /// };
    /// let response = Response::json(data)?;
    ///
    /// // With serde_json::Value
    /// let data = json!({
    ///     "users": [
    ///         {"id": 1, "name": "Alice"},
    ///         {"id": 2, "name": "Bob"}
    ///     ],
    ///     "total": 2
    /// });
    /// let response = Response::json(data)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Error Handling
    /// ```
    /// use ignitia::Response;
    /// use serde_json::json;
    ///
    /// async fn safe_json_handler() -> ignitia::Result<Response> {
    ///     let data = json!({"key": "value"});
    ///
    ///     match Response::json(data) {
    ///         Ok(response) => Ok(response),
    ///         Err(e) => {
    ///             tracing::error!("JSON serialization failed: {}", e);
    ///             Ok(Response::text("Internal server error")
    ///                 .with_status_code(500))
    ///         }
    ///     }
    /// }
    /// ```
    pub fn json<T: Serialize>(data: T) -> Self {
        let body = match serde_json::to_vec(&data) {
            Ok(body) => body,
            Err(e) => {
                tracing::error!("JSON serialization failed: {}", e);
                return Response::text("JSON serialization failed").with_status_code(500);
            }
        };
        let mut response = Self::new(StatusCode::OK);
        response.headers.insert(
            HeaderName::from_static("content-type"),
            HeaderValue::from_static("application/json"),
        );
        response.body = Bytes::from(body);
        response
    }

    /// Creates a plain text response.
    ///
    /// This method creates a response with UTF-8 encoded text and sets the
    /// appropriate content-type header.
    ///
    /// # Parameters
    /// - `text`: The text content (String, &str, or anything that converts to String)
    ///
    /// # Returns
    /// A new response with the text content
    ///
    /// # Examples
    /// ```
    /// use ignitia::Response;
    ///
    /// let response = Response::text("Hello, World!");
    /// assert_eq!(
    ///     response.headers.get("content-type").unwrap(),
    ///     "text/plain; charset=utf-8"
    /// );
    ///
    /// let response = Response::text(format!("User ID: {}", 123));
    /// ```
    ///
    /// ## Multi-line Text
    /// ```
    /// use ignitia::Response;
    ///
    /// let text = r#"
    /// Line 1
    /// Line 2
    /// Line 3
    /// "#;
    /// let response = Response::text(text);
    /// ```
    #[inline]
    pub fn text(text: impl Into<String>) -> Self {
        let mut response = Self::new(StatusCode::OK);
        response.headers.insert(
            HeaderName::from_static("content-type"),
            HeaderValue::from_static("text/plain; charset=utf-8"),
        );
        response.body = Bytes::from(text.into());
        response
    }

    /// Creates an HTML response.
    ///
    /// This method creates a response with HTML content and sets the appropriate
    /// content-type header with UTF-8 charset.
    ///
    /// # Parameters
    /// - `html`: The HTML content (String, &str, or anything that converts to String)
    ///
    /// # Returns
    /// A new response with the HTML content
    ///
    /// # Examples
    /// ```
    /// use ignitia::Response;
    ///
    /// let html = r#"
    /// <!DOCTYPE html>
    /// <html>
    /// <head>
    ///     <title>Hello Page</title>
    ///     <meta charset="UTF-8">
    /// </head>
    /// <body>
    ///     <h1>Hello, World!</h1>
    ///     <p>Welcome to our website!</p>
    /// </body>
    /// </html>
    /// "#;
    ///
    /// let response = Response::html(html);
    /// assert_eq!(
    ///     response.headers.get("content-type").unwrap(),
    ///     "text/html; charset=utf-8"
    /// );
    /// ```
    ///
    /// ## Dynamic HTML Generation
    /// ```
    /// use ignitia::Response;
    ///
    /// fn generate_user_page(username: &str, email: &str) -> Response {
    ///     let html = format!(r#"
    ///     <!DOCTYPE html>
    ///     <html>
    ///     <head><title>User Profile</title></head>
    ///     <body>
    ///         <h1>User Profile</h1>
    ///         <p><strong>Username:</strong> {}</p>
    ///         <p><strong>Email:</strong> {}</p>
    ///     </body>
    ///     </html>
    ///     "#, username, email);
    ///
    ///     Response::html(html)
    /// }
    /// ```
    ///
    /// ## Security Note
    /// When generating HTML with user input, always escape the input to prevent XSS:
    /// ```
    /// use ignitia::Response;
    ///
    /// fn safe_html_response(user_input: &str) -> Response {
    ///     // Escape user input (you would use a proper HTML escape function)
    ///     let escaped_input = user_input
    ///         .replace('&', "&amp;")
    ///         .replace('<', "&lt;")
    ///         .replace('>', "&gt;")
    ///         .replace('"', "&quot;")
    ///         .replace('\'', "&#x27;");
    ///
    ///     let html = format!("<p>Hello, {}</p>", escaped_input);
    ///     Response::html(html)
    /// }
    /// ```
    #[inline]
    pub fn html(html: impl Into<String>) -> Self {
        let mut response = Self::new(StatusCode::OK);
        response.headers.insert(
            HeaderName::from_static("content-type"),
            HeaderValue::from_static("text/html; charset=utf-8"),
        );
        response.body = Bytes::from(html.into());
        response
    }

    /// Creates a temporary redirect response (HTTP 302 Found).
    ///
    /// This is the most commonly used redirect method. The client will make a new request
    /// to the provided location, but the original URL should be used for future requests.
    /// The HTTP method may change to GET for the redirected request.
    ///
    /// # Arguments
    ///
    /// * `location` - The URL to redirect to
    ///
    /// # Examples
    ///
    /// ## Basic Usage
    /// ```
    /// use ignitia::Response;
    ///
    /// let response = Response::redirect("/dashboard");
    /// assert_eq!(response.status, ignitia::StatusCode::FOUND);
    /// assert_eq!(
    ///     response.headers.get("location").unwrap(),
    ///     "/dashboard"
    /// );
    /// ```
    ///
    /// ## Redirect After Login
    /// ```
    /// use ignitia::Response;
    ///
    /// async fn login_handler() -> ignitia::Result<Response> {
    ///     // Authenticate user...
    ///     Ok(Response::redirect("/dashboard"))
    /// }
    /// ```
    ///
    /// ## Conditional Redirect
    /// ```
    /// use ignitia::Response;
    ///
    /// fn redirect_based_on_role(user_role: &str) -> Response {
    ///     match user_role {
    ///         "admin" => Response::redirect("/admin/dashboard"),
    ///         "user" => Response::redirect("/user/profile"),
    ///         _ => Response::redirect("/login"),
    ///     }
    /// }
    /// ```
    #[inline]
    pub fn redirect(location: impl Into<String>) -> Self {
        Self::redirect_with_status(StatusCode::FOUND, location)
    }

    /// Creates a permanent redirect response (HTTP 301 Moved Permanently).
    ///
    /// Use this when a resource has permanently moved to a new location. Search engines
    /// and browsers will update their records to use the new URL. The HTTP method may
    /// change to GET for the redirected request.
    ///
    /// # Arguments
    ///
    /// * `location` - The new permanent URL location
    ///
    /// # Examples
    ///
    /// ## Basic Permanent Redirect
    /// ```
    /// use ignitia::Response;
    ///
    /// let response = Response::permanent_redirect("/new-location");
    /// assert_eq!(response.status, ignitia::StatusCode::MOVED_PERMANENTLY);
    /// ```
    ///
    /// ## Redirecting Old URLs
    /// ```
    /// use ignitia::Response;
    ///
    /// async fn handle_old_blog_url() -> ignitia::Result<Response> {
    ///     // Old blog structure: /blog/2023/article-title
    ///     // New blog structure: /articles/article-title
    ///     Ok(Response::permanent_redirect("/articles/migrating-to-new-blog"))
    /// }
    /// ```
    ///
    /// ## SEO-Friendly Redirects
    /// ```
    /// use ignitia::Response;
    ///
    /// fn redirect_old_product_page(old_id: u32, new_slug: &str) -> Response {
    ///     // Permanently redirect old product IDs to new slug-based URLs
    ///     Response::permanent_redirect(&format!("/products/{}", new_slug))
    /// }
    /// ```
    #[inline]
    pub fn permanent_redirect(location: impl Into<String>) -> Self {
        Self::redirect_with_status(StatusCode::MOVED_PERMANENTLY, location)
    }

    /// Creates a redirect response with a custom HTTP status code.
    ///
    /// This method allows you to specify any redirect status code (3xx series).
    /// The response includes an HTML fallback page for browsers that don't
    /// automatically follow redirects.
    ///
    /// # Arguments
    ///
    /// * `status` - The HTTP status code for the redirect (typically 3xx)
    /// * `location` - The URL to redirect to
    ///
    /// # Examples
    ///
    /// ## Custom Status Redirect
    /// ```
    /// use ignitia::{Response, StatusCode};
    ///
    /// let response = Response::redirect_with_status(
    ///     StatusCode::FOUND,
    ///     "/custom-redirect"
    /// );
    /// ```
    ///
    /// ## Multiple Choice Redirect
    /// ```
    /// use ignitia::{Response, StatusCode};
    ///
    /// fn handle_ambiguous_request() -> Response {
    ///     Response::redirect_with_status(
    ///         StatusCode::MULTIPLE_CHOICES,
    ///         "/choose-option"
    ///     )
    /// }
    /// ```
    ///
    /// ## Temporary Maintenance Redirect
    /// ```
    /// use ignitia::{Response, StatusCode};
    ///
    /// fn maintenance_redirect() -> Response {
    ///     Response::redirect_with_status(
    ///         StatusCode::TEMPORARY_REDIRECT,
    ///         "/maintenance"
    ///     )
    /// }
    /// ```
    pub fn redirect_with_status(status: StatusCode, location: impl Into<String>) -> Self {
        let location_str = location.into();

        let mut response = Self::new(status);
        response.headers.insert(
            header::LOCATION,
            HeaderValue::from_str(&location_str).unwrap_or_else(|_| HeaderValue::from_static("/")),
        );

        // Add a simple HTML body for browsers that don't handle redirects automatically
        let html_body = format!(
            r#"<!DOCTYPE html>
    <html>
    <head>
        <title>Redirect</title>
        <meta http-equiv="refresh" content="0; url={}">
    </head>
    <body>
        <p>Redirecting to <a href="{}">{}</a></p>
    </body>
    </html>"#,
            html_escape(&location_str),
            html_escape(&location_str),
            html_escape(&location_str)
        );

        response.headers.insert(
            header::CONTENT_TYPE,
            HeaderValue::from_static("text/html; charset=utf-8"),
        );
        response.body = bytes::Bytes::from(html_body);

        response
    }

    /// Creates a "See Other" redirect response (HTTP 303 See Other).
    ///
    /// This redirect is ideal for the POST-redirect-GET pattern, where after
    /// processing a POST request, you redirect the client to a GET endpoint.
    /// This prevents duplicate form submissions if the user refreshes the page.
    ///
    /// # Arguments
    ///
    /// * `location` - The URL to redirect to (typically a GET endpoint)
    ///
    /// # Examples
    ///
    /// ## POST-Redirect-GET Pattern
    /// ```
    /// use ignitia::Response;
    ///
    /// async fn process_form() -> ignitia::Result<Response> {
    ///     // Process form data...
    ///     // Save to database...
    ///
    ///     // Redirect to success page to prevent duplicate submissions
    ///     Ok(Response::see_other("/form-success"))
    /// }
    /// ```
    ///
    /// ## After User Registration
    /// ```
    /// use ignitia::Response;
    ///
    /// async fn register_user() -> ignitia::Result<Response> {
    ///     // Create new user account...
    ///
    ///     // Redirect to welcome page
    ///     Ok(Response::see_other("/welcome"))
    /// }
    /// ```
    ///
    /// ## Shopping Cart Checkout
    /// ```
    /// use ignitia::Response;
    ///
    /// async fn checkout_handler() -> ignitia::Result<Response> {
    ///     // Process payment...
    ///     // Update inventory...
    ///
    ///     // Redirect to order confirmation
    ///     Ok(Response::see_other("/order-confirmation"))
    /// }
    /// ```
    #[inline]
    pub fn see_other(location: impl Into<String>) -> Self {
        Self::redirect_with_status(StatusCode::SEE_OTHER, location)
    }

    /// Creates a temporary redirect that preserves the HTTP method (HTTP 307 Temporary Redirect).
    ///
    /// Unlike 302 redirects, this guarantees that the client will use the same HTTP method
    /// when making the redirected request. Use this when the method preservation is important.
    ///
    /// # Arguments
    ///
    /// * `location` - The temporary URL to redirect to
    ///
    /// # Examples
    ///
    /// ## Method-Preserving Redirect
    /// ```
    /// use ignitia::Response;
    ///
    /// async fn api_endpoint() -> ignitia::Result<Response> {
    ///     // Temporarily redirect POST to another server
    ///     Ok(Response::temporary_redirect("/api/v2/endpoint"))
    /// }
    /// ```
    ///
    /// ## Load Balancing Redirect
    /// ```
    /// use ignitia::Response;
    ///
    /// fn balance_load() -> Response {
    ///     // Redirect to less busy server while preserving method
    ///     Response::temporary_redirect("https://server2.example.com/api")
    /// }
    /// ```
    #[inline]
    pub fn temporary_redirect(location: impl Into<String>) -> Self {
        Self::redirect_with_status(StatusCode::TEMPORARY_REDIRECT, location)
    }

    /// Creates a permanent redirect that preserves the HTTP method (HTTP 308 Permanent Redirect).
    ///
    /// This is like 301 but guarantees the client will use the same HTTP method.
    /// Use this for permanent moves where method preservation is crucial.
    ///
    /// # Arguments
    ///
    /// * `location` - The new permanent URL
    ///
    /// # Examples
    ///
    /// ## API Version Migration
    /// ```
    /// use ignitia::Response;
    ///
    /// async fn old_api_endpoint() -> ignitia::Result<Response> {
    ///     // Permanently moved to new API version, preserve HTTP method
    ///     Ok(Response::permanent_redirect_308("/api/v2/users"))
    /// }
    /// ```
    #[inline]
    pub fn permanent_redirect_308(location: impl Into<String>) -> Self {
        Self::redirect_with_status(StatusCode::PERMANENT_REDIRECT, location)
    }

    /// Creates a redirect response without an HTML body (useful for APIs).
    ///
    /// This method creates a minimal redirect response with only the necessary headers,
    /// making it ideal for REST APIs or situations where you don't want the HTML fallback.
    ///
    /// # Arguments
    ///
    /// * `status` - The HTTP status code for the redirect
    /// * `location` - The URL to redirect to
    ///
    /// # Examples
    ///
    /// ## API Redirect
    /// ```
    /// use ignitia::{Response, StatusCode};
    ///
    /// async fn api_redirect() -> ignitia::Result<Response> {
    ///     Ok(Response::redirect_empty(
    ///         StatusCode::FOUND,
    ///         "https://api.example.com/v2/endpoint"
    ///     ))
    /// }
    /// ```
    ///
    /// ## Minimal Redirect
    /// ```
    /// use ignitia::{Response, StatusCode};
    ///
    /// fn lightweight_redirect() -> Response {
    ///     Response::redirect_empty(
    ///         StatusCode::MOVED_PERMANENTLY,
    ///         "/new-location"
    ///     )
    /// }
    /// ```
    pub fn redirect_empty(status: StatusCode, location: impl Into<String>) -> Self {
        let location_str = location.into();

        let mut response = Self::new(status);
        response.headers.insert(
            header::LOCATION,
            HeaderValue::from_str(&location_str).unwrap_or_else(|_| HeaderValue::from_static("/")),
        );

        response
    }

    /// Convenience method for redirecting to a login page.
    ///
    /// Creates a temporary redirect (302) to the specified login path.
    /// This is a commonly used pattern in web applications for authentication flows.
    ///
    /// # Arguments
    ///
    /// * `login_path` - The path to the login page
    ///
    /// # Examples
    ///
    /// ## Basic Login Redirect
    /// ```
    /// use ignitia::Response;
    ///
    /// async fn protected_handler() -> ignitia::Result<Response> {
    ///     // Check authentication...
    ///     if !user_authenticated {
    ///         return Ok(Response::redirect_to_login("/auth/login"));
    ///     }
    ///
    ///     // Continue with protected logic...
    ///     Ok(Response::text("Welcome to protected area"))
    /// }
    /// ```
    ///
    /// ## With Return URL
    /// ```
    /// use ignitia::Response;
    ///
    /// fn redirect_with_return_url(current_path: &str) -> Response {
    ///     let login_url = format!("/login?return_to={}",
    ///         urlencoding::encode(current_path));
    ///     Response::redirect_to_login(login_url)
    /// }
    /// ```
    #[inline]
    pub fn redirect_to_login(login_path: impl Into<String>) -> Self {
        Self::redirect(login_path)
    }

    /// Convenience method for redirecting after a successful POST request.
    ///
    /// Uses HTTP 303 (See Other) to implement the POST-redirect-GET pattern,
    /// preventing duplicate form submissions when users refresh the page.
    ///
    /// # Arguments
    ///
    /// * `location` - The success page URL to redirect to
    ///
    /// # Examples
    ///
    /// ## Form Submission Success
    /// ```
    /// use ignitia::Response;
    ///
    /// async fn contact_form_handler() -> ignitia::Result<Response> {
    ///     // Process contact form...
    ///     // Send email...
    ///     // Save to database...
    ///
    ///     Ok(Response::redirect_after_post("/contact/thank-you"))
    /// }
    /// ```
    ///
    /// ## E-commerce Order
    /// ```
    /// use ignitia::Response;
    ///
    /// async fn place_order() -> ignitia::Result<Response> {
    ///     // Process order...
    ///     // Charge payment...
    ///     // Update inventory...
    ///
    ///     Ok(Response::redirect_after_post("/orders/success"))
    /// }
    /// ```
    #[inline]
    pub fn redirect_after_post(location: impl Into<String>) -> Self {
        Self::see_other(location)
    }

    /// Convenience method for redirecting moved content.
    ///
    /// Creates a permanent redirect (301) for content that has been permanently moved.
    /// This is ideal for SEO as search engines will update their indexes.
    ///
    /// # Arguments
    ///
    /// * `new_location` - The new permanent location of the content
    ///
    /// # Examples
    ///
    /// ## Content Migration
    /// ```
    /// use ignitia::Response;
    ///
    /// async fn old_article_handler() -> ignitia::Result<Response> {
    ///     // Article has moved to new URL structure
    ///     Ok(Response::redirect_moved("/articles/2023/new-article-slug"))
    /// }
    /// ```
    ///
    /// ## Domain Migration
    /// ```
    /// use ignitia::Response;
    ///
    /// fn redirect_to_new_domain() -> Response {
    ///     Response::redirect_moved("https://newdomain.com/same-path")
    /// }
    /// ```
    #[inline]
    pub fn redirect_moved(new_location: impl Into<String>) -> Self {
        Self::permanent_redirect(new_location)
    }

    /// Sets cache control header with specified max-age value.
    ///
    /// This method adds a `Cache-Control` header to the response with the specified
    /// maximum age in seconds. The cache control header instructs browsers, CDNs,
    /// and other caching systems how long to cache this response before considering
    /// it stale and requiring revalidation.
    ///
    /// # Parameters
    /// - `max_age`: Cache lifetime in seconds (0 = no caching)
    ///
    /// # HTTP Header Generated
    /// Creates: `Cache-Control: max-age={max_age}`
    ///
    /// # Common Cache Durations
    /// - **0**: No caching (immediate expiration)
    /// - **300**: 5 minutes (dynamic API responses)
    /// - **3600**: 1 hour (semi-static content)
    /// - **86400**: 24 hours (daily updated content)
    /// - **2592000**: 30 days (monthly content)
    /// - **31536000**: 1 year (static assets with versioning)
    ///
    /// # Examples
    ///
    /// ## API Response Caching
    /// ```
    /// use ignitia::Response;
    /// use serde_json::json;
    ///
    /// async fn user_profile() -> ignitia::Result<Response> {
    ///     let profile = get_user_profile().await?;
    ///
    ///     Response::json(profile)?
    ///         .with_cache_control(1800) // Cache for 30 minutes
    /// }
    /// ```
    ///
    /// ## Static Asset Caching
    /// ```
    /// async fn serve_css() -> Response {
    ///     Response::text_static(include_str!("styles.css"))
    ///         .with_cache_control(31536000) // Cache for 1 year
    /// }
    /// ```
    ///
    /// ## No-Cache for Sensitive Data
    /// ```
    /// async fn user_balance() -> ignitia::Result<Response> {
    ///     let balance = get_current_balance().await?;
    ///
    ///     Response::json(balance)?
    ///         .with_cache_control(0) // Never cache sensitive financial data
    /// }
    /// ```
    #[inline]
    pub fn with_cache_control(mut self, max_age: u64) -> Self {
        self.headers.insert(
            http::header::CACHE_CONTROL,
            HeaderValue::from_str(&format!("max-age={}", max_age)).unwrap(),
        );
        self
    }

    /// Generates a unique cache key for this response based on request URI and ETag.
    ///
    /// Creates a cache key that uniquely identifies this response for storage in
    /// cache systems like Redis, Memcached, or CDN edge caches. The key combines
    /// the request URI with the response's ETag header (if present) to ensure
    /// cache invalidation when content changes.
    ///
    /// # Key Format
    /// `cache_{request_uri}_{etag_or_default}`
    ///
    /// # Parameters
    /// - `request_uri`: The URI path of the original request
    ///
    /// # Cache Key Strategy
    /// - Uses request URI as the primary identifier
    /// - Includes ETag header value for content versioning
    /// - Falls back to "default" if no ETag is present
    /// - Ensures unique keys for different content versions
    ///
    /// # Use Cases
    /// - **CDN Cache Keys**: Identifying cached responses in CDN systems
    /// - **Application Cache**: Storing responses in Redis/Memcached
    /// - **Cache Invalidation**: Targeting specific cached entries for removal
    /// - **Analytics**: Tracking cache hit/miss ratios per endpoint
    ///
    /// # Examples
    ///
    /// ## Basic Cache Key Generation
    /// ```
    /// use ignitia::Response;
    ///
    /// let response = Response::json(user_data)?
    ///     .with_header("etag", "\"abc123\"");
    ///
    /// let cache_key = response.cache_key("/api/users/123");
    /// // Returns: "cache_/api/users/123_abc123"
    /// ```
    ///
    /// ## Cache Storage Integration
    /// ```
    /// async fn cached_response(uri: &str) -> ignitia::Result<Response> {
    ///     let response = Response::json(expensive_computation().await)?;
    ///     let cache_key = response.cache_key(uri);
    ///
    ///     // Store in Redis for future requests
    ///     redis_client.set(&cache_key, &response.body).await?;
    ///
    ///     Ok(response)
    /// }
    /// ```
    ///
    /// ## Cache Invalidation
    /// ```
    /// async fn invalidate_user_cache(user_id: u64) {
    ///     let pattern = format!("cache_/api/users/{}_*", user_id);
    ///     redis_client.delete_pattern(&pattern).await;
    /// }
    /// ```
    pub fn cache_key(&self, request_uri: &str) -> String {
        format!(
            "cache_{}_{}",
            request_uri,
            self.headers
                .get("etag")
                .and_then(|v| v.to_str().ok())
                .unwrap_or("default")
        )
    }

    /// Extracts the max-age value from the Cache-Control header.
    ///
    /// Parses the `Cache-Control` header to extract the `max-age` directive value,
    /// which indicates how many seconds the response should be cached. Returns 0
    /// if no valid max-age directive is found or if the header is malformed.
    ///
    /// # Parsing Logic
    /// 1. Retrieves `Cache-Control` header value
    /// 2. Searches for `max-age=` directive
    /// 3. Extracts numeric value after the equals sign
    /// 4. Handles comma-separated directives correctly
    /// 5. Returns 0 for invalid or missing values
    ///
    /// # Return Value
    /// - **> 0**: Cache lifetime in seconds
    /// - **0**: No caching or invalid header
    ///
    /// # Examples
    ///
    /// ## Reading Cache Duration
    /// ```
    /// use ignitia::Response;
    ///
    /// let response = Response::json(data)?
    ///     .with_cache_control(3600);
    ///
    /// assert_eq!(response.cache_max_age(), 3600);
    /// ```
    ///
    /// ## Conditional Processing Based on Cache Duration
    /// ```
    /// async fn process_response(response: &Response) {
    ///     let cache_duration = response.cache_max_age();
    ///
    ///     match cache_duration {
    ///         0 => {
    ///             // No caching - always fetch fresh
    ///             log::info!("Response not cacheable");
    ///         }
    ///         1..=300 => {
    ///             // Short-term cache - good for dynamic content
    ///             log::info!("Short-term cache: {} seconds", cache_duration);
    ///         }
    ///         301..=3600 => {
    ///             // Medium-term cache - semi-static content
    ///             log::info!("Medium-term cache: {} seconds", cache_duration);
    ///         }
    ///         _ => {
    ///             // Long-term cache - static assets
    ///             log::info!("Long-term cache: {} seconds", cache_duration);
    ///         }
    ///     }
    /// }
    /// ```
    ///
    /// ## Cache Validation Logic
    /// ```
    /// fn should_serve_from_cache(response: &Response, cached_at: SystemTime) -> bool {
    ///     let max_age = response.cache_max_age();
    ///     if max_age == 0 {
    ///         return false; // Never cache
    ///     }
    ///
    ///     let elapsed = cached_at.elapsed().unwrap_or_default();
    ///     elapsed.as_secs() < max_age
    /// }
    /// ```
    pub fn cache_max_age(&self) -> u64 {
        self.headers
            .get("cache-control")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.split("max-age=").nth(1))
            .and_then(|v| v.split(',').next())
            .and_then(|v| v.trim().parse().ok())
            .unwrap_or(0)
    }

    /// Determines if this response is cacheable based on status and headers.
    ///
    /// Analyzes the response to determine if it should be cached by browsers,
    /// CDNs, and other caching systems. A response is considered cacheable if:
    /// 1. The HTTP status indicates success (2xx range)
    /// 2. The Cache-Control header contains a valid `max-age` directive
    /// 3. The max-age value is greater than 0
    ///
    /// # Cacheability Rules
    /// - **Success Status Required**: Only 2xx status codes are cacheable
    /// - **Valid Cache-Control**: Must have `max-age=` directive
    /// - **Non-Zero Duration**: `max-age=0` indicates no caching
    /// - **Header Presence**: Missing Cache-Control header = not cacheable
    ///
    /// # Returns
    /// - `true`: Response should be cached by clients and intermediaries
    /// - `false`: Response should not be cached (fetch fresh each time)
    ///
    /// # Examples
    ///
    /// ## Conditional Cache Storage
    /// ```
    /// use ignitia::Response;
    ///
    /// async fn handle_api_request() -> ignitia::Result<Response> {
    ///     let response = Response::json(get_data().await)?
    ///         .with_cache_control(1800);
    ///
    ///     if response.is_cacheable() {
    ///         // Store in application cache
    ///         cache_service.store(&response).await?;
    ///         log::info!("Response cached for {} seconds", response.cache_max_age());
    ///     } else {
    ///         log::info!("Response not cacheable - serving fresh");
    ///     }
    ///
    ///     Ok(response)
    /// }
    /// ```
    ///
    /// ## CDN Integration
    /// ```
    /// fn configure_cdn_headers(mut response: Response) -> Response {
    ///     if response.is_cacheable() {
    ///         // Add CDN-specific headers for cacheable responses
    ///         response.headers.insert("x-cdn-cache", HeaderValue::from_static("HIT"));
    ///         response.headers.insert("x-cache-duration",
    ///             HeaderValue::from_str(&response.cache_max_age().to_string()).unwrap());
    ///     } else {
    ///         // Ensure CDN doesn't cache non-cacheable responses
    ///         response.headers.insert("x-cdn-cache", HeaderValue::from_static("BYPASS"));
    ///     }
    ///     response
    /// }
    /// ```
    ///
    /// ## Performance Monitoring
    /// ```
    /// fn log_cache_metrics(response: &Response, endpoint: &str) {
    ///     if response.is_cacheable() {
    ///         metrics::increment_counter("cacheable_responses", &[("endpoint", endpoint)]);
    ///         metrics::histogram("cache_duration_seconds", response.cache_max_age() as f64);
    ///     } else {
    ///         metrics::increment_counter("non_cacheable_responses", &[("endpoint", endpoint)]);
    ///     }
    /// }
    /// ```
    ///
    /// ## Error Response Handling
    /// ```
    /// fn create_error_response(error: &AppError) -> Response {
    ///     let response = Response::json(error.to_json())
    ///         .unwrap_or_else(|_| Response::server_error());
    ///
    ///     // Error responses are typically not cacheable
    ///     assert!(!response.is_cacheable());
    ///
    ///     response
    /// }
    /// ```
    pub fn is_cacheable(&self) -> bool {
        self.status.is_success()
            && self
                .headers
                .get("cache-control")
                .and_then(|v| v.to_str().ok())
                .map(|v| v.contains("max-age=") && !v.contains("max-age=0"))
                .unwrap_or(false)
    }
}

pub use builder::ResponseBuilder;

use crate::error::{Error, ErrorResponse};

impl From<Error> for Response {
    /// Converts an Error into an HTTP Response.
    ///
    /// This implementation automatically converts framework errors into proper
    /// HTTP responses with JSON formatting and appropriate status codes.
    ///
    /// # Parameters
    /// - `err`: The error to convert
    ///
    /// # Returns
    /// An HTTP response representing the error
    ///
    /// # Error Response Format
    /// The generated response contains:
    /// - Appropriate HTTP status code
    /// - JSON body with error details
    /// - Proper content-type headers
    /// - Timestamp information
    ///
    /// # Examples
    /// ```
    /// use ignitia::{Error, Response};
    /// use http::StatusCode;
    ///
    /// // Convert a NotFound error
    /// let error = Error::NotFound("User not found".to_string());
    /// let response = Response::from(error);
    /// assert_eq!(response.status, StatusCode::NOT_FOUND);
    ///
    /// // The response body will be JSON:
    /// // {
    /// //   "error": "Not Found",
    /// //   "message": "User not found",
    /// //   "status": 404,
    /// //   "error_type": "not_found",
    /// //   "timestamp": "2023-01-01T12:00:00Z"
    /// // }
    /// ```
    fn from(err: Error) -> Self {
        let status = err.status_code();
        let error_response = err.to_response(true);

        // Try JSON first, fallback to plain text
        match serde_json::to_vec(&error_response) {
            Ok(json_body) => {
                let mut response = Response::new(status);
                response.headers.insert(
                    http::header::CONTENT_TYPE,
                    http::HeaderValue::from_static("application/json"),
                );
                response.body = bytes::Bytes::from(json_body);
                response
            }
            Err(_) => {
                let mut response = Response::new(status);
                response.headers.insert(
                    http::header::CONTENT_TYPE,
                    http::HeaderValue::from_static("text/plain; charset=utf-8"),
                );
                response.body = bytes::Bytes::from(err.to_string());
                response
            }
        }
    }
}

// Enhanced response methods
impl Response {
    /// Creates a JSON error response from an error.
    ///
    /// This method provides more control over error response generation than
    /// the automatic From implementation. It always returns JSON and provides
    /// better error handling for serialization failures.
    ///
    /// # Type Parameters
    /// - `E`: Error type that can be converted to framework Error
    ///
    /// # Parameters
    /// - `error`: The error to convert to a response
    ///
    /// # Returns
    /// - `Ok(Response)`: Successfully created error response
    /// - `Err(Error)`: JSON serialization error
    ///
    /// # Examples
    /// ```
    /// use ignitia::{Response, Error};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let error = Error::Validation("Email format is invalid".to_string());
    /// let response = Response::error_json(error)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn error_json<E: Into<Error>>(error: E) -> crate::Result<Self> {
        let err = error.into();
        let status = err.status_code();
        let error_response = err.to_response(true);

        let mut response = Self::new(status);
        response.headers.insert(
            http::header::CONTENT_TYPE,
            http::HeaderValue::from_static("application/json"),
        );
        response.body = bytes::Bytes::from(serde_json::to_vec(&error_response)?);
        Ok(response)
    }

    /// Creates a validation error response with multiple error messages.
    ///
    /// This method creates a structured validation error response that can
    /// contain multiple validation failure messages.
    ///
    /// # Parameters
    /// - `messages`: Vector of validation error messages
    ///
    /// # Returns
    /// - `Ok(Response)`: Successfully created validation error response
    /// - `Err(Error)`: JSON serialization error
    ///
    /// # Examples
    /// ```
    /// use ignitia::Response;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let validation_errors = vec![
    ///     "Name is required".to_string(),
    ///     "Email format is invalid".to_string(),
    ///     "Password must be at least 8 characters".to_string(),
    /// ];
    ///
    /// let response = Response::validation_error(validation_errors)?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Response Format
    /// The generated response has this structure:
    /// ```
    /// {
    ///   "error": "Validation Failed",
    ///   "message": "Name is required, Email format is invalid, Password must be at least 8 characters",
    ///   "status": 400,
    ///   "error_type": "validation_error",
    ///   "error_code": "VALIDATION_FAILED",
    ///   "metadata": {
    ///     "validation_errors": ["Name is required", "Email format is invalid", "Password must be at least 8 characters"]
    ///   },
    ///   "timestamp": "2023-01-01T12:00:00Z"
    /// }
    /// ```
    ///
    /// ## Usage in Form Validation
    /// ```
    /// use ignitia::{Response, Request, Result};
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize)]
    /// struct UserForm {
    ///     name: String,
    ///     email: String,
    ///     password: String,
    /// }
    ///
    /// async fn validate_user_form(req: Request) -> Result<Response> {
    ///     let form: UserForm = req.json()?;
    ///     let mut errors = Vec::new();
    ///
    ///     if form.name.trim().is_empty() {
    ///         errors.push("Name is required".to_string());
    ///     }
    ///
    ///     if !form.email.contains('@') {
    ///         errors.push("Invalid email format".to_string());
    ///     }
    ///
    ///     if form.password.len() < 8 {
    ///         errors.push("Password must be at least 8 characters".to_string());
    ///     }
    ///
    ///     if !errors.is_empty() {
    ///         return Response::validation_error(errors);
    ///     }
    ///
    ///     Ok(Response::json(serde_json::json!({
    ///         "message": "User created successfully"
    ///     }))?)
    /// }
    /// ```
    pub fn validation_error(messages: Vec<String>) -> crate::Result<Self> {
        let error_response = ErrorResponse {
            error: "Validation Failed".to_string(),
            message: messages.join(", "),
            status: 400,
            error_type: Some("validation_error".to_string()),
            error_code: Some("VALIDATION_FAILED".to_string()),
            metadata: Some(serde_json::json!({
                "validation_errors": messages
            })),
            timestamp: Some(chrono::Utc::now().to_rfc3339()),
        };

        let mut response = Self::new(StatusCode::BAD_REQUEST);
        response.headers.insert(
            http::header::CONTENT_TYPE,
            http::HeaderValue::from_static("application/json"),
        );
        response.body = bytes::Bytes::from(serde_json::to_vec(&error_response)?);
        Ok(response)
    }
}

// Helper function to escape HTML entities
fn html_escape(input: &str) -> String {
    input
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#x27;")
}