uptrakit-web-api-types 0.0.4

Shared HTTP request/response types for the Uptrakit web API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
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
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use uptrakit_shared_types::command_validation::validate_command_length;
use uptrakit_shared_types::{PluginRole, PluginTypeId};
use uuid::Uuid;

use crate::pagination::PaginationParams;
use crate::plugin_configs::CreatePluginConfigRequest;
use crate::validation::{Validate, ValidationError};

fn default_execution_site() -> String {
    "auto".to_string()
}

#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(try_from = "serde_json::Value", into = "serde_json::Value")]
pub struct JsonObjectMap(serde_json::Map<String, serde_json::Value>);

impl TryFrom<serde_json::Value> for JsonObjectMap {
    type Error = ValidationError;

    fn try_from(value: serde_json::Value) -> Result<Self, Self::Error> {
        crate::json_object::parse_json_object(value, "config_override").map(Self)
    }
}

impl JsonObjectMap {
    pub fn new(value: serde_json::Map<String, serde_json::Value>) -> Self {
        Self(value)
    }

    pub fn is_object(&self) -> bool {
        true
    }

    pub fn as_object(&self) -> &serde_json::Map<String, serde_json::Value> {
        &self.0
    }
}

impl From<JsonObjectMap> for serde_json::Value {
    fn from(value: JsonObjectMap) -> Self {
        serde_json::Value::Object(value.0)
    }
}

#[derive(Debug, Clone, Default, PartialEq)]
pub enum IconUrlPatch {
    #[default]
    Keep,
    Set(String),
    Clear,
}

impl IconUrlPatch {
    pub fn is_keep(&self) -> bool {
        matches!(self, Self::Keep)
    }

    pub fn from_json(value: Option<&serde_json::Value>) -> Result<Self, ValidationError> {
        match value {
            None => Ok(Self::Keep),
            Some(serde_json::Value::Null) => Ok(Self::Clear),
            Some(serde_json::Value::String(url)) => Ok(Self::Set(url.clone())),
            Some(_) => Err(ValidationError {
                field: "icon_url",
                message: "icon_url must be null, a string, or omitted".to_string(),
            }),
        }
    }
}

impl Serialize for IconUrlPatch {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Self::Keep | Self::Clear => serializer.serialize_none(),
            Self::Set(url) => url.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for IconUrlPatch {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Ok(match Option::<String>::deserialize(deserializer)? {
            Some(url) => Self::Set(url),
            None => Self::Clear,
        })
    }
}

#[derive(Clone, Debug, Default, PartialEq)]
pub enum JsonObjectMapPatch {
    #[default]
    Keep,
    Set(JsonObjectMap),
    Clear,
}

impl JsonObjectMapPatch {
    pub fn is_keep(&self) -> bool {
        matches!(self, Self::Keep)
    }

    pub fn as_set(&self) -> Option<&JsonObjectMap> {
        match self {
            Self::Set(value) => Some(value),
            Self::Keep | Self::Clear => None,
        }
    }

    pub fn into_option(self) -> Option<JsonObjectMap> {
        match self {
            Self::Set(value) => Some(value),
            Self::Keep | Self::Clear => None,
        }
    }

    pub fn resolve(self, current: Option<JsonObjectMap>) -> Option<JsonObjectMap> {
        match self {
            Self::Keep => current,
            Self::Set(value) => Some(value),
            Self::Clear => None,
        }
    }
}

impl Serialize for JsonObjectMapPatch {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Self::Keep | Self::Clear => serializer.serialize_none(),
            Self::Set(value) => value.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for JsonObjectMapPatch {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Ok(match Option::<JsonObjectMap>::deserialize(deserializer)? {
            Some(value) => Self::Set(value),
            None => Self::Clear,
        })
    }
}

fn validate_https_icon_url(url: &str) -> Result<(), ValidationError> {
    if url.len() > 2048 {
        return Err(ValidationError {
            field: "icon_url",
            message: "icon_url must not exceed 2048 characters".to_string(),
        });
    }
    if !url.starts_with("https://") {
        return Err(ValidationError {
            field: "icon_url",
            message: "icon_url must start with https://".to_string(),
        });
    }

    Ok(())
}

/// Create a new software item (catalog entry only — no plugin coupling).
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct CreateSoftwareItemRequest {
    /// Display name (e.g. "1Password").
    pub name: String,
    /// Whether this item is featured (shown prominently). Defaults to true for manual creation.
    #[serde(default = "crate::default_featured")]
    pub featured: bool,
    /// Optional HTTPS URL to an icon/logo image for this software item.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon_url: Option<String>,
}

/// Partial update for a software item. Only `name` and `featured` are updatable.
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct UpdateSoftwareItemRequest {
    pub name: Option<String>,
    pub featured: Option<bool>,
    /// Set, clear, or keep the icon URL.
    ///
    /// - Absent JSON key: keep existing value.
    /// - `null`: clear the icon URL.
    /// - String: set a new HTTPS URL.
    #[serde(default, skip_serializing_if = "IconUrlPatch::is_keep")]
    #[cfg_attr(feature = "openapi", schema(value_type = Option<String>))]
    pub icon_url: IconUrlPatch,
}

/// Per-host plugin assignment used when assigning hosts to a software item.
///
/// Each host assignment contains a list of role-specific plugin assignments.
/// At minimum, a `detect_version` role should be provided for version tracking.
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct HostSoftwareAssignment {
    pub host_id: Uuid,
    /// Role-specific plugin assignments for this host-software pair.
    pub plugins: Vec<HostPluginRoleAssignment>,
}

/// A plugin assignment for a specific role on a host-software pair.
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct HostPluginRoleAssignment {
    /// The role this plugin serves (e.g. `detect_version`, `fetch_releases`, `execute_update`).
    pub role: PluginRole,
    /// Ordinal for hook roles; must be `0` for non-hook roles. Defaults to `0`.
    #[serde(default)]
    pub ordinal: i32,
    /// UUID of an existing plugin config to use.
    pub plugin_config_id: Option<Uuid>,
    /// Inline plugin config to create (mutually exclusive with `plugin_config_id`).
    pub plugin_config: Option<CreatePluginConfigRequest>,
    /// Plugin-specific package identifier.
    pub package_identifier: String,
    /// Plugin-specific overrides merged onto the base config at resolution time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config_override: Option<JsonObjectMap>,
    /// Controls where this plugin's operation is executed.
    /// - `"auto"`: system decides based on plugin capabilities (default)
    /// - `"agent"`: always run on the agent
    /// - `"controller"`: always run on the controller (only valid for `fetch_releases`)
    #[serde(default = "default_execution_site")]
    pub execution_site: String,
}

/// Assign one or more hosts to a software item, each with its own plugin info.
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct AssignHostsRequest {
    pub host_assignments: Vec<HostSoftwareAssignment>,
}

/// Update a single role assignment for an existing host–software-item pair.
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct UpdateHostAssignmentRequest {
    /// The role to update (e.g. `detect_version`, `fetch_releases`, `execute_update`).
    pub role: PluginRole,
    /// Ordinal for this assignment. For hook roles (pre/post_update_hook), multiple
    /// assignments with different ordinals are allowed. For non-hook roles, this
    /// must be `0`. Defaults to `0`.
    #[serde(default)]
    pub ordinal: i32,
    /// UUID of an existing plugin config to use.
    pub plugin_config_id: Option<Uuid>,
    /// Inline plugin config to create and link. At most one of plugin_config_id,
    /// plugin_config, plugin_type may be set; omit all three to keep the existing plugin source.
    pub plugin_config: Option<CreatePluginConfigRequest>,
    /// Plugin type for a truly inline assignment with no shared config row.
    /// At most one source may be set; omitting all three keeps the existing plugin source.
    /// The full plugin config is supplied via `config_override`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plugin_type: Option<PluginTypeId>,
    pub package_identifier: Option<String>,
    /// Omit to keep, send `null` to clear, or send an object to set the override.
    #[serde(default, skip_serializing_if = "JsonObjectMapPatch::is_keep")]
    #[cfg_attr(feature = "openapi", schema(value_type = Option<serde_json::Value>))]
    pub config_override: JsonObjectMapPatch,
    /// Controls where this plugin's operation is executed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub execution_site: Option<String>,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct SoftwareItemResponse {
    pub id: Uuid,
    pub name: String,
    /// Distinct plugin type identifiers from all active host assignments (for display in lists).
    pub plugins: Vec<String>,
    pub featured: bool,
    #[serde(with = "time::serde::rfc3339::option")]
    #[cfg_attr(feature = "openapi", schema(value_type = Option<String>, format = DateTime))]
    pub last_checked_at: Option<OffsetDateTime>,
    pub host_count: u64,
    /// Installed version on the specific host. Present only when the `host_id`
    /// query filter is used; `None` otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub installed_version: Option<String>,
    /// Plugin-provided display version for the installed version. Present only
    /// when the `host_id` query filter is used and the plugin provides one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub installed_display_version: Option<String>,
    /// Latest known version derived as the maximum across all hosts'
    /// `latest_version` values. `None` when no host has a known latest version yet.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub latest_version: Option<String>,
    /// Intentionally left dynamic: payload shape is plugin-defined at the REST boundary.
    /// Present only when the `host_id` query filter is used.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub latest_release_metadata: Option<serde_json::Value>,
    /// `true` when at least one assigned host has an `installed_version` that differs
    /// from its per-host `latest_version` (and both values are known). Uses string
    /// equality — no semver parsing — because version formats are plugin-specific.
    pub update_available: bool,
    #[serde(with = "time::serde::rfc3339")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, format = DateTime))]
    pub created_at: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, format = DateTime))]
    pub updated_at: OffsetDateTime,
    /// Optional HTTPS URL to an icon/logo image.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon_url: Option<String>,
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct SoftwareItemDetailResponse {
    pub id: Uuid,
    pub name: String,
    /// Distinct plugin type identifiers from all active host assignments.
    pub plugins: Vec<String>,
    pub featured: bool,
    #[serde(with = "time::serde::rfc3339::option")]
    #[cfg_attr(feature = "openapi", schema(value_type = Option<String>, format = DateTime))]
    pub last_checked_at: Option<OffsetDateTime>,
    pub host_count: u64,
    /// Latest known version derived as the maximum across all hosts' `latest_version` values.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub latest_version: Option<String>,
    /// `true` when any assigned host has a known `installed_version` that differs from
    /// its per-host `latest_version`.
    pub update_available: bool,
    #[serde(with = "time::serde::rfc3339")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, format = DateTime))]
    pub created_at: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, format = DateTime))]
    pub updated_at: OffsetDateTime,
    /// Optional HTTPS URL to an icon/logo image.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon_url: Option<String>,
    pub hosts: Vec<SoftwareItemHostSummary>,
}

#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct SoftwareItemHostSummary {
    /// Primary key of the `host_software_items` row — unique per link even when the same
    /// host appears multiple times (e.g. two Docker containers from the same image).
    pub id: Uuid,
    pub host_id: Uuid,
    pub hostname: String,
    pub friendly_name: String,
    /// Disambiguates multiple links between the same host and software item
    /// (e.g. different Docker container names sharing the same image).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub qualifier: Option<String>,
    /// Role-specific plugin assignments for this host-software pair.
    pub plugins: Vec<HostPluginRoleSummary>,
    pub installed_version: Option<String>,
    #[serde(with = "time::serde::rfc3339::option")]
    #[cfg_attr(feature = "openapi", schema(value_type = Option<String>, format = DateTime))]
    pub installed_version_detected_at: Option<OffsetDateTime>,
    /// Plugin-provided display version for the installed version (e.g. Docker image publish date).
    /// `None` when the installed version is self-explanatory (semver, etc.).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub installed_display_version: Option<String>,
    /// Per-host latest known version (from the `fetch_releases` role plugin).
    /// `None` when no upstream version has been resolved yet for this host.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub latest_version: Option<String>,
    /// Intentionally left dynamic: payload shape is plugin-defined at the REST boundary.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub latest_release_metadata: Option<serde_json::Value>,
    /// `true` when `installed_version` and `latest_version` are both `Some` and differ.
    pub update_available: bool,
    /// ID of the currently active (queued / pending / in_progress) update for this host,
    /// if any. `None` when no update is running. Used by the UI to show a contextual
    /// status badge and open the live terminal instead of the update confirmation dialog.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub active_update_history_id: Option<Uuid>,
    /// Status of the active update, if any. One of: "queued", "pending",
    /// "in_progress", "awaiting_restart". None when no active update exists.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub active_update_status: Option<String>,
    /// Classification of the available update (security, bugfix, feature, unknown).
    pub update_category: String,
    #[serde(with = "time::serde::rfc3339::option")]
    #[cfg_attr(feature = "openapi", schema(value_type = Option<String>, format = DateTime))]
    pub last_updated_at: Option<OffsetDateTime>,
    #[serde(with = "time::serde::rfc3339")]
    #[cfg_attr(feature = "openapi", schema(value_type = String, format = DateTime))]
    pub linked_at: OffsetDateTime,
}

/// Summary of a plugin role assignment on a host-software pair (read-only).
///
/// When the assignment was created via autodiscovery (package managers),
/// `plugin_config_id` and `plugin_config_name` are `None` — the plugin type
/// is read directly from the HSIP row's `plugin_type` column.
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct HostPluginRoleSummary {
    pub role: PluginRole,
    /// Ordinal (0-based) for hook roles; always 0 for non-hook roles.
    #[serde(default)]
    pub ordinal: i32,
    /// `None` for autodiscovered package-manager assignments (no stored config).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plugin_config_id: Option<Uuid>,
    /// `None` when `plugin_config_id` is `None`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plugin_config_name: Option<String>,
    pub plugin_type: String,
    pub package_identifier: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub config_override: Option<JsonObjectMap>,
    pub execution_site: String,
}

/// Status returned when triggering an update.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum TriggerUpdateStatus {
    /// Agent connected, update sent.
    Pending,
    /// Agent offline, will deliver on reconnect.
    Queued,
    /// Update failed on the controller before any agent execution started.
    Failed,
}

impl std::fmt::Display for TriggerUpdateStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Pending => f.write_str("pending"),
            Self::Queued => f.write_str("queued"),
            Self::Failed => f.write_str("failed"),
        }
    }
}

/// Release asset information for triggering an update.
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct ReleaseAssetInfoRequest {
    pub name: String,
    pub download_url: String,
    pub size: Option<u64>,
}

/// Release information for triggering an update.
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct ReleaseInfoRequest {
    pub tag: String,
    pub release_url: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub assets: Vec<ReleaseAssetInfoRequest>,
}

/// Request body for triggering a software update.
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct TriggerUpdateRequest {
    /// Target version to update to.
    pub to_version: String,
    /// Optional release information (for plugins that need it).
    pub release_info: Option<ReleaseInfoRequest>,
    /// When true, the agent allocates a PTY and keeps stdin open for forwarding.
    #[serde(default)]
    pub interactive: bool,
}

/// Response when triggering a software update.
#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct TriggerUpdateResponse {
    pub update_history_id: Uuid,
    pub status: TriggerUpdateStatus,
}

/// Response when triggering a version check for a software item.
#[derive(Debug, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct TriggerVersionCheckResponse {
    /// Number of agents that were sent version-check messages.
    pub agents_notified: u32,
    /// Number of controller-side `fetch_releases` checks that ran synchronously.
    ///
    /// Non-zero when at least one `fetch_releases` plugin has
    /// `ControllerSideFetchReleases` capability (e.g. GitHub, Docker) and ran
    /// directly on the controller rather than being delegated to an agent.
    #[serde(default)]
    pub controller_checks_run: u32,
    /// Human-readable status message.
    pub message: String,
}

/// Query parameters for listing software items, extending pagination with an optional
/// featured filter.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::IntoParams))]
pub struct ListSoftwareItemsParams {
    /// Page number (1-indexed). Defaults to 1.
    pub page: Option<u64>,
    /// Items per page. Defaults to 20, max 1000.
    pub per_page: Option<u64>,
    /// Filter by featured status. Omit to return all items.
    pub featured: Option<bool>,
    /// Filter by host — only return software items assigned to this host.
    pub host_id: Option<Uuid>,
    /// Filter by update availability.
    ///
    /// - `true`: only items where at least one active host has an update available
    ///   (`installed_version != latest_version`, both non-null).
    /// - `false`: only items where no active host has an update available.
    /// - Omit: no filter.
    pub updatable: Option<bool>,
    /// Filter by plugin type — only return items that have at least one host
    /// assignment using this plugin type (e.g. `"releases.docker"`).
    /// Omit to return items for any plugin type.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub plugin_type: Option<String>,
    /// Filter by name — case-insensitive substring match, max 200 chars.
    /// The server lowercases and escapes LIKE metacharacters before the SQL
    /// bind; the database evaluates `LOWER(name) LIKE ? ESCAPE '\'`.
    /// Empty/whitespace-only values are ignored.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub query: Option<String>,
}

impl ListSoftwareItemsParams {
    /// Convert the pagination fields to a [`PaginationParams`] for resolution.
    pub fn pagination(&self) -> PaginationParams {
        PaginationParams {
            page: self.page,
            per_page: self.per_page,
        }
    }
}

/// Compact summary of a software item used by merge preview responses.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct MergeSoftwareItemSummary {
    pub id: Uuid,
    pub name: String,
    pub host_count: u64,
    pub plugins: Vec<String>,
}

/// Compact summary of a host-software link affected by a merge preview.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct MergeSoftwareItemLinkSummary {
    pub id: Uuid,
    pub host_id: Uuid,
    pub hostname: String,
    pub friendly_name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub qualifier: Option<String>,
}

/// Request payload for previewing a manual merge of software items.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct MergeSoftwareItemsPreviewRequest {
    pub candidate_ids: Vec<Uuid>,
    pub survivor_id: Uuid,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seed_item_id: Option<Uuid>,
}

/// Response payload for previewing a manual merge of software items.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct MergeSoftwareItemsPreviewResponse {
    pub candidates: Vec<MergeSoftwareItemSummary>,
    pub survivor: MergeSoftwareItemSummary,
    pub losers: Vec<MergeSoftwareItemSummary>,
    pub moved_links: Vec<MergeSoftwareItemLinkSummary>,
    pub skipped_duplicate_links: Vec<MergeSoftwareItemLinkSummary>,
    pub candidate_count: u64,
    pub loser_count: u64,
    pub moved_link_count: u64,
    pub skipped_duplicate_link_count: u64,
}

/// Request payload for executing a manual merge of software items.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct MergeSoftwareItemsExecuteRequest {
    pub candidate_ids: Vec<Uuid>,
    pub survivor_id: Uuid,
}

/// Response payload for executing a manual merge of software items.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct MergeSoftwareItemsExecuteResponse {
    pub survivor_id: Uuid,
    pub deleted_ids: Vec<Uuid>,
    pub moved_link_ids: Vec<Uuid>,
    pub skipped_duplicate_link_ids: Vec<Uuid>,
}

impl Validate for CreateSoftwareItemRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        if self.name.trim().is_empty() {
            return Err(ValidationError {
                field: "name",
                message: "name must not be empty".to_string(),
            });
        }
        if let Some(url) = &self.icon_url {
            validate_https_icon_url(url)?;
        }
        Ok(())
    }
}

impl Validate for UpdateSoftwareItemRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        if let IconUrlPatch::Set(url) = &self.icon_url {
            validate_https_icon_url(url)?;
        }
        Ok(())
    }
}

impl Validate for TriggerUpdateRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        validate_command_length(&self.to_version, "to_version").map_err(|message| {
            ValidationError {
                field: "to_version",
                message,
            }
        })?;
        Ok(())
    }
}

impl Validate for HostPluginRoleAssignment {
    fn validate(&self) -> Result<(), ValidationError> {
        if self.package_identifier.trim().is_empty() {
            return Err(ValidationError {
                field: "package_identifier",
                message: "package_identifier must not be empty".to_string(),
            });
        }
        if let Some(cfg) = &self.plugin_config {
            cfg.validate()?;
        }
        Ok(())
    }
}

impl Validate for AssignHostsRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        if self.host_assignments.is_empty() {
            return Err(ValidationError {
                field: "host_assignments",
                message: "host_assignments must not be empty".to_string(),
            });
        }
        if self.host_assignments.len() > crate::batch_actions::MAX_BATCH_SIZE {
            return Err(ValidationError {
                field: "host_assignments",
                message: format!(
                    "host_assignments must contain at most {} entries",
                    crate::batch_actions::MAX_BATCH_SIZE
                ),
            });
        }
        for assignment in &self.host_assignments {
            for plugin in &assignment.plugins {
                plugin.validate()?;
            }
        }
        Ok(())
    }
}

impl Validate for UpdateHostAssignmentRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        let sources = [
            self.plugin_config_id.is_some(),
            self.plugin_config.is_some(),
            self.plugin_type.is_some(),
        ]
        .into_iter()
        .filter(|set| *set)
        .count();
        if sources > 1 {
            return Err(ValidationError {
                field: "plugin_config_id",
                message: "at most one of plugin_config_id, plugin_config, plugin_type may be set"
                    .to_string(),
            });
        }
        if let Some(pkg) = &self.package_identifier
            && pkg.trim().is_empty()
        {
            return Err(ValidationError {
                field: "package_identifier",
                message: "package_identifier must not be empty".to_string(),
            });
        }
        if let Some(cfg) = &self.plugin_config {
            cfg.validate()?;
        }
        Ok(())
    }
}

impl Validate for MergeSoftwareItemsExecuteRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        if self.candidate_ids.is_empty() {
            return Err(ValidationError {
                field: "candidate_ids",
                message: "candidate_ids must not be empty".to_string(),
            });
        }
        Ok(())
    }
}

impl Validate for MergeSoftwareItemsPreviewRequest {
    fn validate(&self) -> Result<(), ValidationError> {
        // Read-only dry-run; ids are typed Uuids. No format/length invariants beyond field types.
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    #![expect(
        clippy::assertions_on_result_states,
        reason = "test assertions — is_ok/is_err provides readable failure messages"
    )]
    use super::*;
    use uptrakit_shared_types::plugin_ids;

    fn sample_uuid() -> Uuid {
        Uuid::parse_str("a1a2a3a4-b1b2-c1c2-d1d2-e1e2e3e4e5e6")
            .expect("hard-coded UUID should be valid")
    }

    fn valid_create_request() -> CreateSoftwareItemRequest {
        CreateSoftwareItemRequest {
            name: "1Password".to_string(),
            featured: true,
            icon_url: None,
        }
    }

    // ── CreateSoftwareItemRequest serialization ──────────────────────

    #[test]
    fn create_software_item_request_round_trip() {
        let req = valid_create_request();
        let json = serde_json::to_string(&req).expect("serialization should succeed");
        let deserialized: CreateSoftwareItemRequest =
            serde_json::from_str(&json).expect("deserialization should succeed");
        assert_eq!(deserialized.name, "1Password");
        assert!(deserialized.featured);
    }

    #[test]
    fn create_software_item_request_default_featured_from_json() {
        let json = serde_json::json!({ "name": "Test" });
        let req: CreateSoftwareItemRequest =
            serde_json::from_value(json).expect("deserialization should succeed");
        assert!(req.featured, "featured should default to true");
    }

    // ── CreateSoftwareItemRequest validation ─────────────────────────

    #[test]
    fn validate_valid_request_passes() {
        let req = valid_create_request();
        assert!(req.validate().is_ok());
    }

    #[test]
    fn validate_empty_name_fails() {
        let req = CreateSoftwareItemRequest {
            name: "".to_string(),
            featured: true,
            icon_url: None,
        };
        let err = req
            .validate()
            .expect_err("empty name should fail validation");
        assert_eq!(err.field, "name");
    }

    #[test]
    fn validate_whitespace_only_name_fails() {
        let req = CreateSoftwareItemRequest {
            name: "   ".to_string(),
            featured: true,
            icon_url: None,
        };
        let err = req
            .validate()
            .expect_err("whitespace-only name should fail validation");
        assert_eq!(err.field, "name");
    }

    #[test]
    fn create_software_item_icon_url_https_passes() {
        let req = CreateSoftwareItemRequest {
            name: "App".to_string(),
            featured: true,
            icon_url: Some("https://example.com/icon.png".to_string()),
        };
        assert!(req.validate().is_ok());
    }

    #[test]
    fn create_software_item_icon_url_http_rejected() {
        let req = CreateSoftwareItemRequest {
            name: "App".to_string(),
            featured: true,
            icon_url: Some("http://example.com/icon.png".to_string()),
        };
        let err = req.validate().expect_err("http URL should fail validation");
        assert_eq!(err.field, "icon_url");
    }

    #[test]
    fn create_software_item_icon_url_none_passes() {
        let req = CreateSoftwareItemRequest {
            name: "App".to_string(),
            featured: true,
            icon_url: None,
        };
        assert!(req.validate().is_ok());
    }

    #[test]
    fn update_software_item_icon_url_https_passes() {
        let req = UpdateSoftwareItemRequest {
            name: None,
            featured: None,
            icon_url: IconUrlPatch::Set("https://example.com/icon.png".to_string()),
        };
        assert!(req.validate().is_ok());
    }

    #[test]
    fn update_software_item_icon_url_null_clears() {
        let req: UpdateSoftwareItemRequest = serde_json::from_value(serde_json::json!({
            "icon_url": null
        }))
        .expect("deserialization should succeed");
        assert!(req.validate().is_ok());
        assert_eq!(req.icon_url, IconUrlPatch::Clear);
    }

    #[test]
    fn update_software_item_icon_url_http_rejected() {
        let req = UpdateSoftwareItemRequest {
            name: None,
            featured: None,
            icon_url: IconUrlPatch::Set("http://example.com/icon.png".to_string()),
        };
        let err = req.validate().expect_err("http URL should fail validation");
        assert_eq!(err.field, "icon_url");
    }

    #[test]
    fn update_software_item_icon_url_patch_parses_set_clear_and_keep() {
        let keep_req: UpdateSoftwareItemRequest =
            serde_json::from_value(serde_json::json!({})).expect("keep request should deserialize");
        let clear_req: UpdateSoftwareItemRequest = serde_json::from_value(serde_json::json!({
            "icon_url": null
        }))
        .expect("clear request should deserialize");
        let set_req: UpdateSoftwareItemRequest = serde_json::from_value(serde_json::json!({
            "icon_url": "https://example.com/icon.png"
        }))
        .expect("set request should deserialize");

        assert_eq!(keep_req.icon_url, IconUrlPatch::Keep);
        assert_eq!(clear_req.icon_url, IconUrlPatch::Clear);
        assert!(matches!(
            set_req.icon_url,
            IconUrlPatch::Set(ref url) if url == "https://example.com/icon.png"
        ));

        assert!(matches!(
            IconUrlPatch::from_json(None).expect("keep"),
            IconUrlPatch::Keep
        ));
        assert!(matches!(
            IconUrlPatch::from_json(Some(&serde_json::Value::Null)).expect("clear"),
            IconUrlPatch::Clear
        ));
        assert!(matches!(
            IconUrlPatch::from_json(Some(&serde_json::json!("https://example.com/icon.png")))
                .expect("set"),
            IconUrlPatch::Set(url) if url == "https://example.com/icon.png"
        ));
    }

    #[test]
    fn update_software_item_icon_url_patch_rejects_invalid_shape() {
        let err = IconUrlPatch::from_json(Some(&serde_json::json!({"url": "https://example.com"})))
            .expect_err("object should be rejected");
        assert_eq!(err.field, "icon_url");
    }

    // ── AssignHostsRequest round-trip ──────────────────────────────

    #[test]
    fn assign_hosts_request_round_trip() {
        let req = AssignHostsRequest {
            host_assignments: vec![
                HostSoftwareAssignment {
                    host_id: sample_uuid(),
                    plugins: vec![
                        HostPluginRoleAssignment {
                            role: PluginRole::DetectVersion,
                            ordinal: 0,
                            plugin_config_id: Some(sample_uuid()),
                            plugin_config: None,
                            package_identifier: "1password".to_string(),
                            config_override: None,
                            execution_site: "auto".to_string(),
                        },
                        HostPluginRoleAssignment {
                            role: PluginRole::FetchReleases,
                            ordinal: 0,
                            plugin_config_id: Some(sample_uuid()),
                            plugin_config: None,
                            package_identifier: "1password".to_string(),
                            config_override: None,
                            execution_site: "auto".to_string(),
                        },
                    ],
                },
                HostSoftwareAssignment {
                    host_id: Uuid::nil(),
                    plugins: vec![HostPluginRoleAssignment {
                        role: PluginRole::ExecuteUpdate,
                        ordinal: 0,
                        plugin_config_id: None,
                        plugin_config: Some(crate::plugin_configs::CreatePluginConfigRequest {
                            name: "Homebrew Casks".to_string(),
                            plugin_type: plugin_ids::PACKAGE_MANAGER_HOMEBREW.clone(),
                            config: serde_json::json!({"package_type": "cask"}),
                            enabled: true,
                        }),
                        package_identifier: "1password-cli".to_string(),
                        config_override: None,
                        execution_site: "agent".to_string(),
                    }],
                },
            ],
        };
        let json = serde_json::to_string(&req).expect("serialization should succeed");
        let deserialized: AssignHostsRequest =
            serde_json::from_str(&json).expect("deserialization should succeed");
        assert_eq!(deserialized.host_assignments.len(), 2);
        assert_eq!(deserialized.host_assignments[0].host_id, sample_uuid());
        assert_eq!(deserialized.host_assignments[0].plugins.len(), 2);
        assert_eq!(
            deserialized.host_assignments[0].plugins[0].package_identifier,
            "1password"
        );
        assert_eq!(deserialized.host_assignments[1].plugins.len(), 1);
        assert!(
            deserialized.host_assignments[1].plugins[0]
                .plugin_config
                .is_some()
        );
    }

    #[test]
    fn host_plugin_role_assignment_defaults_execution_site() {
        let json = serde_json::json!({
            "role": "detect_version",
            "plugin_config_id": sample_uuid(),
            "package_identifier": "nginx"
        });
        let assignment: HostPluginRoleAssignment =
            serde_json::from_value(json).expect("deserialization should succeed");
        assert_eq!(assignment.execution_site, "auto");
        assert_eq!(assignment.role, PluginRole::DetectVersion);
    }

    #[test]
    fn update_host_assignment_request_round_trip() {
        let req = UpdateHostAssignmentRequest {
            role: PluginRole::FetchReleases,
            ordinal: 0,
            plugin_config_id: Some(sample_uuid()),
            plugin_config: None,
            plugin_type: None,
            package_identifier: Some("nginx".to_string()),
            config_override: JsonObjectMapPatch::Set(
                JsonObjectMap::try_from(serde_json::json!({
                    "asset_patterns": ["nginx.*linux"]
                }))
                .expect("object config_override"),
            ),
            execution_site: Some("controller".to_string()),
        };
        let json = serde_json::to_string(&req).expect("serialization should succeed");
        let deserialized: UpdateHostAssignmentRequest =
            serde_json::from_str(&json).expect("deserialization should succeed");
        assert_eq!(deserialized.role, PluginRole::FetchReleases);
        assert_eq!(deserialized.execution_site.as_deref(), Some("controller"));
        assert_eq!(
            deserialized.config_override,
            JsonObjectMapPatch::Set(
                JsonObjectMap::try_from(serde_json::json!({
                    "asset_patterns": ["nginx.*linux"]
                }))
                .expect("object config_override")
            )
        );

        let keep_req: UpdateHostAssignmentRequest = serde_json::from_value(serde_json::json!({
            "role": "fetch_releases"
        }))
        .expect("keep request should deserialize");
        assert_eq!(keep_req.config_override, JsonObjectMapPatch::Keep);

        let clear_req: UpdateHostAssignmentRequest = serde_json::from_value(serde_json::json!({
            "role": "fetch_releases",
            "config_override": null
        }))
        .expect("clear request should deserialize");
        assert_eq!(clear_req.config_override, JsonObjectMapPatch::Clear);
    }

    // ── SoftwareItemResponse ─────────────────────────────────────────

    #[test]
    fn software_item_response_round_trip() {
        use time::macros::datetime;
        let resp = SoftwareItemResponse {
            id: sample_uuid(),
            name: "1Password".to_string(),
            plugins: vec![
                "package-manager.homebrew".to_string(),
                "releases.github".to_string(),
            ],
            featured: true,
            last_checked_at: Some(datetime!(2025-06-01 12:00:00 UTC)),
            host_count: 5,
            installed_version: Some("8.9.0".to_string()),
            installed_display_version: None,
            latest_version: Some("8.10.0".to_string()),
            latest_release_metadata: None,
            update_available: true,
            created_at: datetime!(2025-01-01 00:00:00 UTC),
            updated_at: datetime!(2025-06-01 12:00:00 UTC),
            icon_url: None,
        };
        let json = serde_json::to_string(&resp).expect("serialization should succeed");
        let deserialized: SoftwareItemResponse =
            serde_json::from_str(&json).expect("deserialization should succeed");
        assert_eq!(deserialized.id, sample_uuid());
        assert_eq!(deserialized.name, "1Password");
        assert_eq!(deserialized.host_count, 5);
        assert_eq!(deserialized.plugins.len(), 2);
        assert!(deserialized.featured);
        assert_eq!(deserialized.installed_version.as_deref(), Some("8.9.0"));
        assert_eq!(deserialized.latest_version.as_deref(), Some("8.10.0"));
        assert!(deserialized.update_available);
    }

    #[test]
    fn software_item_response_update_available_false_when_no_latest() {
        use time::macros::datetime;
        let resp = SoftwareItemResponse {
            id: sample_uuid(),
            name: "MyApp".to_string(),
            plugins: vec!["releases.github".to_string()],
            featured: true,
            last_checked_at: None,
            host_count: 1,
            installed_version: None,
            installed_display_version: None,
            latest_version: None,
            latest_release_metadata: None,
            update_available: false,
            created_at: datetime!(2025-01-01 00:00:00 UTC),
            updated_at: datetime!(2025-01-01 00:00:00 UTC),
            icon_url: None,
        };
        let json = serde_json::to_string(&resp).expect("serialization should succeed");
        let deserialized: SoftwareItemResponse =
            serde_json::from_str(&json).expect("deserialization should succeed");
        assert!(deserialized.installed_version.is_none());
        assert!(deserialized.latest_version.is_none());
        assert!(!deserialized.update_available);
        // installed_version and latest_version are skipped when None
        let json_value =
            serde_json::to_value(&resp).expect("serialization to Value should succeed");
        assert!(json_value.get("installed_version").is_none());
        assert!(json_value.get("latest_version").is_none());
    }

    #[test]
    fn software_item_response_empty_plugins() {
        use time::macros::datetime;
        let resp = SoftwareItemResponse {
            id: sample_uuid(),
            name: "Test".to_string(),
            plugins: vec![],
            featured: false,
            last_checked_at: None,
            host_count: 0,
            installed_version: None,
            installed_display_version: None,
            latest_version: None,
            latest_release_metadata: None,
            update_available: false,
            created_at: datetime!(2025-01-01 00:00:00 UTC),
            updated_at: datetime!(2025-01-01 00:00:00 UTC),
            icon_url: None,
        };
        let json = serde_json::to_string(&resp).expect("serialization should succeed");
        let deserialized: SoftwareItemResponse =
            serde_json::from_str(&json).expect("deserialization should succeed");
        assert!(deserialized.plugins.is_empty());
        assert!(deserialized.last_checked_at.is_none());
        assert!(!deserialized.featured);
        assert!(!deserialized.update_available);
    }

    // ── TriggerUpdateRequest / TriggerUpdateResponse ─────────────────

    #[test]
    fn trigger_update_request_round_trip() {
        let req = TriggerUpdateRequest {
            to_version: "2.0.0".to_string(),
            release_info: None,
            interactive: false,
        };
        let json = serde_json::to_string(&req).expect("serialization should succeed");
        let deserialized: TriggerUpdateRequest =
            serde_json::from_str(&json).expect("deserialization should succeed");
        assert_eq!(deserialized.to_version, "2.0.0");
        assert!(deserialized.release_info.is_none());
    }

    #[test]
    fn trigger_update_request_with_release_info() {
        let req = TriggerUpdateRequest {
            to_version: "3.0.0".to_string(),
            release_info: Some(ReleaseInfoRequest {
                tag: "v3.0.0".to_string(),
                release_url: "https://github.com/example/repo/releases/v3.0.0".to_string(),
                assets: vec![ReleaseAssetInfoRequest {
                    name: "binary.tar.gz".to_string(),
                    download_url: "https://example.com/binary.tar.gz".to_string(),
                    size: Some(1024),
                }],
            }),
            interactive: false,
        };
        let json = serde_json::to_string(&req).expect("serialization should succeed");
        let deserialized: TriggerUpdateRequest =
            serde_json::from_str(&json).expect("deserialization should succeed");
        let info = deserialized
            .release_info
            .expect("release_info should be present");
        assert_eq!(info.tag, "v3.0.0");
        assert_eq!(info.assets.len(), 1);
        assert_eq!(info.assets[0].size, Some(1024));
    }

    #[test]
    fn trigger_update_response_round_trip() {
        let resp = TriggerUpdateResponse {
            update_history_id: sample_uuid(),
            status: TriggerUpdateStatus::Pending,
        };
        let json = serde_json::to_string(&resp).expect("serialization should succeed");
        let deserialized: TriggerUpdateResponse =
            serde_json::from_str(&json).expect("deserialization should succeed");
        assert_eq!(deserialized.update_history_id, sample_uuid());
        assert_eq!(deserialized.status, TriggerUpdateStatus::Pending);
    }

    #[test]
    fn trigger_update_response_queued_status() {
        let resp = TriggerUpdateResponse {
            update_history_id: sample_uuid(),
            status: TriggerUpdateStatus::Queued,
        };
        let json_value =
            serde_json::to_value(&resp).expect("serialization to Value should succeed");
        assert_eq!(
            json_value.get("status").and_then(|v| v.as_str()),
            Some("queued")
        );
    }

    #[test]
    fn trigger_update_response_failed_status() {
        let resp = TriggerUpdateResponse {
            update_history_id: sample_uuid(),
            status: TriggerUpdateStatus::Failed,
        };
        let json_value =
            serde_json::to_value(&resp).expect("serialization to Value should succeed");
        assert_eq!(
            json_value.get("status").and_then(|v| v.as_str()),
            Some("failed")
        );
    }

    // ── TriggerVersionCheckResponse ──────────────────────────────────

    #[test]
    fn trigger_version_check_response_round_trip() {
        let resp = TriggerVersionCheckResponse {
            agents_notified: 3,
            controller_checks_run: 0,
            message: "Version check triggered for 3 agents".to_string(),
        };
        let json = serde_json::to_string(&resp).expect("serialization should succeed");
        let deserialized: TriggerVersionCheckResponse =
            serde_json::from_str(&json).expect("deserialization should succeed");
        assert_eq!(deserialized.agents_notified, 3);
        assert_eq!(deserialized.controller_checks_run, 0);
        assert_eq!(deserialized.message, "Version check triggered for 3 agents");
    }

    #[test]
    fn trigger_version_check_response_controller_only() {
        let resp = TriggerVersionCheckResponse {
            agents_notified: 0,
            controller_checks_run: 2,
            message: "Version check completed for 2 item(s) on the controller".to_string(),
        };
        let json = serde_json::to_string(&resp).expect("serialization should succeed");
        let deserialized: TriggerVersionCheckResponse =
            serde_json::from_str(&json).expect("deserialization should succeed");
        assert_eq!(deserialized.agents_notified, 0);
        assert_eq!(deserialized.controller_checks_run, 2);
    }

    #[test]
    fn trigger_version_check_response_controller_checks_run_defaults_to_zero() {
        // Old JSON without controller_checks_run should deserialize with default 0.
        let json = r#"{"agents_notified":1,"message":"ok"}"#;
        let deserialized: TriggerVersionCheckResponse =
            serde_json::from_str(json).expect("deserialization should succeed");
        assert_eq!(deserialized.agents_notified, 1);
        assert_eq!(deserialized.controller_checks_run, 0);
    }

    #[test]
    fn trigger_version_check_response_zero_agents() {
        let resp = TriggerVersionCheckResponse {
            agents_notified: 0,
            controller_checks_run: 0,
            message: "No agents connected".to_string(),
        };
        let json = serde_json::to_string(&resp).expect("serialization should succeed");
        let deserialized: TriggerVersionCheckResponse =
            serde_json::from_str(&json).expect("deserialization should succeed");
        assert_eq!(deserialized.agents_notified, 0);
        assert_eq!(deserialized.controller_checks_run, 0);
    }

    // ── TriggerUpdateStatus Display ──────────────────────────────────

    #[test]
    fn trigger_update_status_display() {
        assert_eq!(TriggerUpdateStatus::Pending.to_string(), "pending");
        assert_eq!(TriggerUpdateStatus::Queued.to_string(), "queued");
        assert_eq!(TriggerUpdateStatus::Failed.to_string(), "failed");
    }

    // ── ListSoftwareItemsParams ──────────────────────────────────────

    #[test]
    fn list_software_items_params_featured_filter() {
        let json = serde_json::json!({ "featured": true });
        let params: ListSoftwareItemsParams =
            serde_json::from_value(json).expect("deserialization should succeed");
        assert_eq!(params.featured, Some(true));
    }

    #[test]
    fn list_software_items_params_no_filter() {
        let params = ListSoftwareItemsParams::default();
        assert!(params.featured.is_none());
        assert!(params.page.is_none());
        assert!(params.per_page.is_none());
    }

    #[test]
    fn list_software_items_params_updatable_filter() {
        let json = serde_json::json!({ "updatable": true });
        let params: ListSoftwareItemsParams =
            serde_json::from_value(json).expect("deserialization should succeed");
        assert_eq!(params.updatable, Some(true));
    }

    #[test]
    fn list_software_items_params_plugin_type_filter() {
        let json = serde_json::json!({ "plugin_type": "releases.docker" });
        let params: ListSoftwareItemsParams =
            serde_json::from_value(json).expect("deserialization should succeed");
        assert_eq!(params.plugin_type.as_deref(), Some("releases.docker"));
    }

    #[test]
    fn list_software_items_params_query_filter() {
        let params: ListSoftwareItemsParams =
            serde_json::from_str(r#"{"query":"node","plugin_type":"releases.docker"}"#)
                .expect("deserialize");
        assert_eq!(params.query.as_deref(), Some("node"));
        assert_eq!(params.plugin_type.as_deref(), Some("releases.docker"));
    }

    #[test]
    fn merge_preview_request_round_trip() {
        let req = MergeSoftwareItemsPreviewRequest {
            candidate_ids: vec![Uuid::nil(), Uuid::new_v4()],
            survivor_id: Uuid::nil(),
            seed_item_id: Some(Uuid::new_v4()),
        };
        let json = serde_json::to_string(&req).expect("serialize");
        let parsed: MergeSoftwareItemsPreviewRequest =
            serde_json::from_str(&json).expect("deserialize");
        assert_eq!(parsed.candidate_ids.len(), 2);
        assert_eq!(parsed.survivor_id, Uuid::nil());
    }

    #[test]
    fn merge_preview_response_round_trip() {
        let resp = MergeSoftwareItemsPreviewResponse {
            candidates: vec![MergeSoftwareItemSummary {
                id: Uuid::nil(),
                name: "Node.js".to_string(),
                host_count: 2,
                plugins: vec!["releases.github".to_string()],
            }],
            survivor: MergeSoftwareItemSummary {
                id: Uuid::new_v4(),
                name: "Node.js LTS".to_string(),
                host_count: 4,
                plugins: vec!["releases.github".to_string()],
            },
            losers: vec![MergeSoftwareItemSummary {
                id: Uuid::new_v4(),
                name: "Node".to_string(),
                host_count: 1,
                plugins: vec![],
            }],
            moved_links: vec![MergeSoftwareItemLinkSummary {
                id: Uuid::new_v4(),
                host_id: Uuid::new_v4(),
                hostname: "host-a".to_string(),
                friendly_name: "Host A".to_string(),
                qualifier: None,
            }],
            skipped_duplicate_links: vec![MergeSoftwareItemLinkSummary {
                id: Uuid::new_v4(),
                host_id: Uuid::new_v4(),
                hostname: "host-b".to_string(),
                friendly_name: "Host B".to_string(),
                qualifier: Some("docker".to_string()),
            }],
            candidate_count: 1,
            loser_count: 1,
            moved_link_count: 1,
            skipped_duplicate_link_count: 1,
        };
        let json = serde_json::to_string(&resp).expect("serialize");
        let parsed: MergeSoftwareItemsPreviewResponse =
            serde_json::from_str(&json).expect("deserialize");
        assert_eq!(parsed.candidates.len(), 1);
        assert_eq!(parsed.losers.len(), 1);
        assert_eq!(parsed.moved_links.len(), 1);
        assert_eq!(parsed.candidate_count, 1);
        assert_eq!(parsed.loser_count, 1);
        assert_eq!(parsed.moved_link_count, 1);
        assert_eq!(parsed.skipped_duplicate_link_count, 1);
    }

    #[test]
    fn merge_preview_response_serializes_empty_arrays() {
        let resp = MergeSoftwareItemsPreviewResponse {
            candidates: vec![],
            survivor: MergeSoftwareItemSummary {
                id: Uuid::nil(),
                name: "Node.js".to_string(),
                host_count: 0,
                plugins: vec![],
            },
            losers: vec![],
            moved_links: vec![],
            skipped_duplicate_links: vec![],
            candidate_count: 0,
            loser_count: 0,
            moved_link_count: 0,
            skipped_duplicate_link_count: 0,
        };
        let json = serde_json::to_value(&resp).expect("serialize");
        assert!(json["candidates"].as_array().is_some());
        assert!(json["survivor"]["plugins"].as_array().is_some());
        assert!(json["losers"].as_array().is_some());
        assert!(json["moved_links"].as_array().is_some());
        assert!(json["skipped_duplicate_links"].as_array().is_some());
        assert_eq!(json["candidate_count"], 0);
    }

    #[test]
    fn merge_execute_response_round_trip() {
        let resp = MergeSoftwareItemsExecuteResponse {
            survivor_id: Uuid::nil(),
            deleted_ids: vec![Uuid::new_v4()],
            moved_link_ids: vec![Uuid::new_v4()],
            skipped_duplicate_link_ids: vec![Uuid::new_v4()],
        };
        let json = serde_json::to_string(&resp).expect("serialize");
        let parsed: MergeSoftwareItemsExecuteResponse =
            serde_json::from_str(&json).expect("deserialize");
        assert_eq!(parsed.deleted_ids.len(), 1);
    }

    // ── Validate impls ────────────────────────────────────────────────

    fn valid_plugin_type_id() -> PluginTypeId {
        PluginTypeId::new("apt")
    }

    fn valid_update_host_assignment() -> UpdateHostAssignmentRequest {
        UpdateHostAssignmentRequest {
            role: PluginRole::DetectVersion,
            ordinal: 0,
            plugin_config_id: Some(sample_uuid()),
            plugin_config: None,
            plugin_type: None,
            package_identifier: Some("nginx".to_string()),
            config_override: JsonObjectMapPatch::Keep,
            execution_site: None,
        }
    }

    #[test]
    fn trigger_update_rejects_empty_and_oversized_to_version() {
        let empty = TriggerUpdateRequest {
            to_version: String::new(),
            release_info: None,
            interactive: false,
        };
        assert_eq!(empty.validate().err().map(|e| e.field), Some("to_version"));

        let oversized = TriggerUpdateRequest {
            to_version: "v".repeat(9000),
            release_info: None,
            interactive: false,
        };
        assert_eq!(
            oversized.validate().err().map(|e| e.field),
            Some("to_version")
        );
    }

    #[test]
    fn trigger_update_accepts_normal_version() {
        let req = TriggerUpdateRequest {
            to_version: "1.2.3".to_string(),
            release_info: None,
            interactive: false,
        };
        assert!(req.validate().is_ok());
    }

    #[test]
    fn assign_hosts_rejects_empty_and_oversized_assignment_lists() {
        let empty = AssignHostsRequest {
            host_assignments: vec![],
        };
        assert_eq!(
            empty.validate().err().map(|e| e.field),
            Some("host_assignments")
        );

        let one = HostSoftwareAssignment {
            host_id: sample_uuid(),
            plugins: vec![],
        };
        let oversized = AssignHostsRequest {
            host_assignments: std::iter::repeat_with(|| HostSoftwareAssignment {
                host_id: one.host_id,
                plugins: vec![],
            })
            .take(101)
            .collect(),
        };
        assert_eq!(
            oversized.validate().err().map(|e| e.field),
            Some("host_assignments")
        );
    }

    #[test]
    fn merge_preview_validate_is_ok() {
        let req = MergeSoftwareItemsPreviewRequest {
            candidate_ids: vec![sample_uuid()],
            survivor_id: sample_uuid(),
            seed_item_id: None,
        };
        assert!(req.validate().is_ok());
    }

    #[test]
    fn update_host_assignment_accepts_zero_and_one_config_source() {
        // Zero sources = "keep the existing plugin source" (spec item 1).
        let mut zero = valid_update_host_assignment();
        zero.plugin_config_id = None;
        zero.plugin_config = None;
        zero.plugin_type = None;
        assert!(zero.validate().is_ok());

        let one = valid_update_host_assignment();
        assert!(one.validate().is_ok());
    }

    #[test]
    fn update_host_assignment_rejects_two_config_sources() {
        let mut two = valid_update_host_assignment();
        two.plugin_config_id = Some(sample_uuid());
        two.plugin_type = Some(valid_plugin_type_id());
        let err = two.validate().expect_err("two sources must be rejected");
        assert_eq!(err.field, "plugin_config_id");
    }

    #[test]
    fn host_plugin_role_assignment_rejects_empty_package_identifier() {
        let assignment = HostPluginRoleAssignment {
            role: PluginRole::DetectVersion,
            ordinal: 0,
            plugin_config_id: Some(sample_uuid()),
            plugin_config: None,
            package_identifier: String::new(),
            config_override: None,
            execution_site: "auto".to_string(),
        };
        assert_eq!(
            assignment.validate().err().map(|e| e.field),
            Some("package_identifier")
        );
    }

    #[test]
    fn merge_execute_rejects_empty_candidate_ids() {
        let req = MergeSoftwareItemsExecuteRequest {
            candidate_ids: vec![],
            survivor_id: sample_uuid(),
        };
        assert_eq!(req.validate().err().map(|e| e.field), Some("candidate_ids"));
    }

    #[test]
    fn merge_execute_accepts_non_empty_candidate_ids() {
        let req = MergeSoftwareItemsExecuteRequest {
            candidate_ids: vec![sample_uuid()],
            survivor_id: sample_uuid(),
        };
        assert!(req.validate().is_ok());
    }
}