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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
# πŸ“– EduVerse API Documentation β€” Courses / Assignments / Labs

> **Purpose**: Complete Flutter frontend integration guide.
> **Base URL**: `http://<host>:3001` (default port `3001`)
> **Auth**: Most endpoints require `Authorization: Bearer <JWT>` header.
> **Content-Type**: `application/json` unless otherwise noted (file uploads use `multipart/form-data`).

---

## Table of Contents

1. [Global Information](#1-global-information)
2. [Enums Reference](#2-enums-reference)
3. [Courses Module](#3-courses-module)
4. [Course Sections Module](#4-course-sections-module)
5. [Course Schedules Module](#5-course-schedules-module)
6. [Assignments Module](#6-assignments-module)
7. [Labs Module](#7-labs-module)
8. [Role-Based Access Matrix](#8-role-based-access-matrix)
9. [Error Handling](#9-error-handling)
10. [Flutter Integration Tips](#10-flutter-integration-tips)
11. [Course Materials & Video Lectures Module](#11-course-materials--video-lectures-module)
12. [Course Structure Module](#12-course-structure-module)
13. [YouTube Integration Module](#13-youtube-integration-module)

---

## 1. Global Information

### 1.1 Authentication

All **authenticated endpoints** require the header:

```
Authorization: Bearer <access_token>
```

The token is obtained from `POST /api/auth/login`.

### 1.2 Roles

| Role Enum Value | Display Name | Description |
|---|---|---|
| `student` | Student | Regular student users |
| `instructor` | Instructor | Faculty members |
| `teaching_assistant` | TA | Teaching assistants |
| `admin` | Admin | Administrative staff |
| `it_admin` | IT Admin | Full system access |
| `department_head` | Department Head | Department leadership |

### 1.3 Pagination Response Shape

All paginated endpoints return:

```json
{
  "data": [ /* array of items */ ],
  "meta": {
    "total": 150,       // integer β€” total matching records
    "page": 1,          // integer β€” current page number
    "limit": 20,        // integer β€” items per page
    "totalPages": 8     // integer β€” total number of pages
  }
}
```

### 1.4 Validation Rules

The API uses `class-validator` with:
- `whitelist: true` β€” unknown properties are **stripped**
- `forbidNonWhitelisted: true` β€” unknown properties cause **400 error**
- `transform: true` β€” query strings auto-converted to proper types

---

## 2. Enums Reference

### 2.1 Course Enums

#### CourseLevel
| Value | Description |
|---|---|
| `FRESHMAN` | Freshman-level course |
| `SOPHOMORE` | Sophomore-level course |
| `JUNIOR` | Junior-level course |
| `SENIOR` | Senior-level course |
| `GRADUATE` | Graduate-level course |

#### CourseStatus
| Value | Description |
|---|---|
| `ACTIVE` | Course is currently active |
| `INACTIVE` | Course is inactive |
| `ARCHIVED` | Course is archived |

#### SectionStatus
| Value | Description |
|---|---|
| `OPEN` | Section accepting enrollments |
| `CLOSED` | Section manually closed |
| `FULL` | Section at max capacity |
| `CANCELLED` | Section cancelled |

#### ScheduleType
| Value | Description |
|---|---|
| `LECTURE` | Lecture session |
| `LAB` | Laboratory session |
| `TUTORIAL` | Tutorial/recitation session |
| `EXAM` | Examination session |

#### DayOfWeek
| Value |
|---|
| `MONDAY` |
| `TUESDAY` |
| `WEDNESDAY` |
| `THURSDAY` |
| `FRIDAY` |
| `SATURDAY` |
| `SUNDAY` |

### 2.2 Assignment Enums

#### SubmissionType
| Value | Description |
|---|---|
| `file` | File-based submission |
| `text` | Text-based submission |
| `link` | Link/URL submission |
| `multiple` | Combination of types |

#### AssignmentStatus
| Value | Description |
|---|---|
| `draft` | Not visible to students |
| `published` | Visible and accepting submissions |
| `closed` | No longer accepting submissions |
| `archived` | Hidden from all views |

> **Status Transitions**: `draft` β†’ `published` β†’ `closed` β†’ `archived` (one-way only)

#### SubmissionStatus
| Value | Description |
|---|---|
| `submitted` | Student has submitted |
| `graded` | Submission has been graded |
| `returned` | Returned to student for review |
| `resubmit` | Student must resubmit |

### 2.3 Lab Enums

#### LabStatus
| Value | Description |
|---|---|
| `draft` | Not visible to students |
| `published` | Visible and accepting submissions |
| `closed` | No longer accepting submissions |
| `archived` | Hidden from all views |

#### LabSubmissionStatus
| Value | Description |
|---|---|
| `submitted` | Student has submitted |
| `graded` | Submission has been graded |
| `returned` | Returned to student |
| `resubmit` | Student must resubmit |

#### LabAttendanceStatus
| Value | Description |
|---|---|
| `present` | Student was present |
| `absent` | Student was absent |
| `excused` | Excused absence |
| `late` | Student arrived late |

---

## 3. Courses Module

**Base Path**: `/api/courses`

> **Authentication**: Courses listing/viewing endpoints are **public** (no auth required).
> Course creation/update/delete endpoints need authentication and specific roles.

---

### 3.1 List All Courses

```
GET /api/courses
```

**Auth Required**: ❌ No (Public)
**Roles**: All (public endpoint)

#### Query Parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `departmentId` | `integer` | ❌ | β€” | Filter by department ID |
| `level` | `string` | ❌ | β€” | Filter by course level enum (e.g. `FRESHMAN`, `GRADUATE`) |
| `status` | `string` | ❌ | β€” | Filter by `CourseStatus` enum (`ACTIVE`, `INACTIVE`, `ARCHIVED`) |
| `search` | `string` | ❌ | β€” | Search in course name or code (partial match) |
| `page` | `integer` | ❌ | `1` | Page number (1-indexed) |
| `limit` | `integer` | ❌ | `20` | Items per page (max 100) |

#### Response `200 OK`

```json
{
  "data": [
    {
      "id": 1,                              // number β€” Course ID (bigint)
      "departmentId": 3,                    // number β€” FK to departments
      "name": "Introduction to CS",         // string β€” Course name
      "code": "CS101",                      // string β€” Unique course code
      "description": "Fundamentals of...",  // string | null β€” Description
      "credits": 3,                         // number β€” Credit hours (1-6)
      "level": "FRESHMAN",                  // string β€” CourseLevel enum
      "syllabusUrl": "https://...",         // string | null β€” Syllabus URL
      "instructorId": 5,                    // number | null β€” Assigned instructor
      "taIds": [1, 2],                      // number[] | null β€” Assigned TA IDs
      "status": "ACTIVE",                   // string β€” CourseStatus enum
      "createdAt": "2025-01-15T10:00:00Z",  // string (ISO 8601) β€” Creation timestamp
      "updatedAt": "2025-01-15T10:00:00Z",  // string (ISO 8601) β€” Last update
      "department": {                        // object β€” Joined department info
        "id": 3,
        "name": "Computer Science",
        "code": "CS"
      }
    }
  ],
  "meta": {
    "total": 42,
    "page": 1,
    "limit": 20,
    "totalPages": 3
  }
}
```

---

### 3.2 Get Courses by Department

```
GET /api/courses/department/:deptId
```

**Auth Required**: ❌ No (Public)
**Roles**: All

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `deptId` | `integer` | βœ… | Department ID |

#### Response `200 OK`

Returns an **array** of course objects (same shape as items in `data` array above, including `department` relation).

#### Error Responses

| Status | Description |
|---|---|
| `404` | Department not found |

---

### 3.3 Get Course by ID

```
GET /api/courses/:id
```

**Auth Required**: ❌ No (Public)
**Roles**: All

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Course ID |

#### Response `200 OK`

```json
{
  "id": 1,
  "departmentId": 3,
  "name": "Introduction to CS",
  "code": "CS101",
  "description": "Fundamentals of programming...",
  "credits": 3,
  "level": "FRESHMAN",
  "syllabusUrl": "https://example.com/syllabus.pdf",
  "instructorId": 5,
  "taIds": [1, 2],
  "status": "ACTIVE",
  "createdAt": "2025-01-15T10:00:00Z",
  "updatedAt": "2025-01-15T10:00:00Z",
  "department": {
    "id": 3,
    "name": "Computer Science",
    "code": "CS"
  },
  "prerequisites": [],         // CoursePrerequisite[] β€” loaded relation
  "sections": [],              // CourseSection[] β€” loaded relation
  "prerequisitesCount": 0,     // number β€” count of prerequisites
  "sectionsCount": 2           // number β€” count of active sections
}
```

#### Error Responses

| Status | Description |
|---|---|
| `404` | Course not found |

---

### 3.4 Create Course

```
POST /api/courses
```

**Auth Required**: βœ… Yes
**Roles**: `admin`, `it_admin`, `instructor`

#### Request Body (`application/json`)

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `departmentId` | `number` | βœ… | Must exist | Department to assign course to |
| `name` | `string` | βœ… | β€” | Course name |
| `code` | `string` | βœ… | 2-10 uppercase alphanumeric (`/^[A-Z0-9]{2,10}$/`) | Unique course code |
| `description` | `string` | βœ… | β€” | Course description |
| `credits` | `integer` | βœ… | 1–6 | Credit hours |
| `level` | `string` | βœ… | `CourseLevel` enum | Course level |
| `syllabusUrl` | `string` | ❌ | Valid URL | Syllabus URL |
| `instructorId` | `number` | ❌ | Must reference valid user | Instructor user ID |
| `taIds` | `number[]` | ❌ | Array of valid user IDs | TA user IDs |

#### Example Request

```json
{
  "departmentId": 1,
  "name": "Introduction to Computer Science",
  "code": "CS101",
  "description": "Fundamentals of programming and computational thinking.",
  "credits": 3,
  "level": "FRESHMAN",
  "syllabusUrl": "https://example.com/syllabus/cs101.pdf",
  "instructorId": 5,
  "taIds": [10, 11]
}
```

#### Response `201 Created`

Returns the created course object (same shape as Get Course by ID, without `prerequisitesCount`/`sectionsCount`).

#### Error Responses

| Status | Description |
|---|---|
| `400` | Invalid input data / validation failure |
| `404` | Department not found |
| `409` | Course code already exists in department |

---

### 3.5 Update Course

```
PATCH /api/courses/:id
```

**Auth Required**: βœ… Yes
**Roles**: `admin`, `it_admin`, `instructor`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Course ID |

#### Request Body (`application/json`) β€” All fields optional

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `name` | `string` | ❌ | β€” | Updated course name |
| `description` | `string` | ❌ | β€” | Updated description |
| `credits` | `integer` | ❌ | 1–6 | Updated credit hours |
| `level` | `string` | ❌ | `CourseLevel` enum | Updated course level |
| `syllabusUrl` | `string` | ❌ | β€” | Updated syllabus URL |
| `status` | `string` | ❌ | `CourseStatus` enum | Change course status |
| `instructorId` | `number` | ❌ | β€” | Change instructor |
| `taIds` | `number[]` | ❌ | β€” | Change TAs |

#### Response `200 OK`

Returns the updated course object.

#### Error Responses

| Status | Description |
|---|---|
| `400` | Invalid input data |
| `404` | Course not found |

---

### 3.6 Delete Course (Soft Delete)

```
DELETE /api/courses/:id
```

**Auth Required**: βœ… Yes
**Roles**: `admin`, `it_admin`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Course ID |

#### Response `204 No Content`

Empty body.

#### Error Responses

| Status | Description |
|---|---|
| `400` | Cannot delete course with active enrollments |
| `404` | Course not found |

---

### 3.7 Get Course Prerequisites

```
GET /api/courses/:id/prerequisites
```

**Auth Required**: ❌ No (Public)
**Roles**: All

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Course ID |

#### Response `200 OK`

```json
[
  {
    "id": 1,                          // number β€” Prerequisite record ID
    "courseId": 5,                     // number β€” The course that has this prerequisite
    "prerequisiteCourseId": 2,         // number β€” The required prereq course ID
    "isMandatory": true,               // boolean β€” Whether this prereq is mandatory
    "prerequisiteCourse": {            // object β€” Joined prerequisite course info
      "id": 2,
      "name": "Programming Basics",
      "code": "CS100",
      "level": "FRESHMAN"
    },
    "createdAt": "2025-01-10T08:00:00Z"   // string (ISO 8601)
  }
]
```

---

### 3.8 Add Prerequisite

```
POST /api/courses/:id/prerequisites
```

**Auth Required**: βœ… Yes
**Roles**: `admin`, `it_admin`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Course ID to add prerequisite to |

#### Request Body

| Field | Type | Required | Description |
|---|---|---|---|
| `prerequisiteCourseId` | `number` | βœ… | ID of the prerequisite course |
| `isMandatory` | `boolean` | βœ… | Whether this prerequisite is mandatory |

#### Example Request

```json
{
  "prerequisiteCourseId": 2,
  "isMandatory": true
}
```

#### Response `201 Created`

Returns the created prerequisite record.

#### Error Responses

| Status | Description |
|---|---|
| `400` | Circular dependency detected / Self-prerequisite |
| `404` | Course or prerequisite course not found |
| `409` | Prerequisite already exists |

---

### 3.9 Remove Prerequisite

```
DELETE /api/courses/:id/prerequisites/:prereqId
```

**Auth Required**: βœ… Yes
**Roles**: `admin`, `it_admin`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Course ID |
| `prereqId` | `integer` | βœ… | Prerequisite record ID |

#### Response `204 No Content`

Empty body.

---

## 4. Course Sections Module

**Base Path**: `/api/sections`

---

### 4.1 Get Sections by Course

```
GET /api/sections/course/:courseId
```

**Auth Required**: ❌ No (Public)
**Roles**: All

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |

#### Query Parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `semesterId` | `integer` | ❌ | β€” | Filter by semester |

#### Response `200 OK`

```json
[
  {
    "id": 11,                              // number β€” Section ID (bigint)
    "courseId": 1,                          // number β€” FK to courses
    "semesterId": 1,                       // number β€” FK to semesters
    "sectionNumber": "1",                  // string β€” Section number
    "maxCapacity": 30,                     // number β€” Maximum students
    "currentEnrollment": 25,               // number β€” Currently enrolled
    "location": "Room A101",               // string | null β€” Room/location
    "status": "OPEN",                      // string β€” SectionStatus enum
    "createdAt": "2025-01-15T10:00:00Z",
    "updatedAt": "2025-01-15T10:00:00Z",
    "course": {
      "id": 1,
      "name": "Introduction to CS",
      "code": "CS101"
    },
    "semester": {
      "id": 1,
      "name": "Fall 2025",
      "startDate": "2025-09-01",
      "endDate": "2025-12-15"
    },
    "schedules": [
      {
        "id": 1,
        "dayOfWeek": "MONDAY",            // DayOfWeek enum
        "startTime": "09:00",             // string (HH:mm)
        "endTime": "10:30",               // string (HH:mm)
        "room": "A101",                   // string | null
        "building": "Main Building",      // string | null
        "scheduleType": "LECTURE"          // ScheduleType enum
      }
    ]
  }
]
```

---

### 4.2 Get Section by ID

```
GET /api/sections/:id
```

**Auth Required**: ❌ No (Public)
**Roles**: All

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Section ID |

#### Response `200 OK`

Same shape as a single item from the array above (includes `course`, `semester`, `schedules` relations).

---

### 4.3 Create Section

```
POST /api/sections
```

**Auth Required**: βœ… Yes
**Roles**: `admin`, `it_admin`, `instructor`

#### Request Body

| Field | Type | Required | Default | Constraints | Description |
|---|---|---|---|---|---|
| `courseId` | `number` | βœ… | β€” | Must exist | Course to create section for |
| `semesterId` | `number` | βœ… | β€” | Must exist | Semester ID |
| `sectionNumber` | `integer` | ❌ | Auto-generated | >= 1 | Section number |
| `maxCapacity` | `integer` | βœ… | β€” | >= 1 | Maximum student capacity |
| `currentEnrollment` | `integer` | ❌ | `0` | >= 0 | Current enrollment count |
| `location` | `string` | ❌ | `null` | β€” | Room/location |

#### Example Request

```json
{
  "courseId": 1,
  "semesterId": 1,
  "maxCapacity": 30,
  "location": "Room A101"
}
```

#### Response `201 Created`

Returns the created section object.

#### Error Responses

| Status | Description |
|---|---|
| `400` | Invalid input data |
| `404` | Course or semester not found |
| `409` | Section number already exists for this course/semester combo |

---

### 4.4 Update Section

```
PATCH /api/sections/:id
```

**Auth Required**: βœ… Yes
**Roles**: `admin`, `it_admin`, `instructor` (section owner)

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Section ID |

#### Request Body β€” All fields optional

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `maxCapacity` | `integer` | ❌ | >= 1, cannot be less than current enrollment | Updated max capacity |
| `currentEnrollment` | `integer` | ❌ | >= 0 | Updated enrollment count |
| `location` | `string` | ❌ | β€” | Updated location |
| `status` | `string` | ❌ | `SectionStatus` enum | Change section status |

#### Response `200 OK`

Returns the updated section object.

---

### 4.5 Update Section Enrollment Count

```
PATCH /api/sections/:id/enrollment
```

**Auth Required**: βœ… Yes
**Roles**: `admin`, `it_admin`, `instructor`

> Typically called automatically by the enrollment system.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Section ID |

#### Request Body

| Field | Type | Required | Description |
|---|---|---|---|
| `currentEnrollment` | `number` | βœ… | New enrollment count |

#### Response `200 OK`

Returns the updated section object with recalculated status.

---

## 5. Course Schedules Module

**Base Path**: `/api/schedules`

---

### 5.1 Get Schedules by Section

```
GET /api/schedules/section/:sectionId
```

**Auth Required**: ❌ No (Public)
**Roles**: All

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `sectionId` | `integer` | βœ… | Section ID |

#### Response `200 OK`

```json
[
  {
    "id": 1,                        // number β€” Schedule ID
    "sectionId": 11,                // number β€” FK to sections
    "dayOfWeek": "MONDAY",          // string β€” DayOfWeek enum
    "startTime": "09:00",           // string β€” HH:mm format (24-hour)
    "endTime": "10:30",             // string β€” HH:mm format (24-hour)
    "room": "A101",                 // string | null
    "building": "Main Building",    // string | null
    "scheduleType": "LECTURE",      // string β€” ScheduleType enum
    "createdAt": "2025-01-15T10:00:00Z"
  }
]
```

---

### 5.2 Get Schedule by ID

```
GET /api/schedules/:id
```

**Auth Required**: ❌ No (Public)
**Roles**: All

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Schedule ID |

#### Response `200 OK`

Returns single schedule object with `section` relation included.

---

### 5.3 Create Schedule

```
POST /api/schedules/section/:sectionId
```

**Auth Required**: βœ… Yes
**Roles**: `admin`, `it_admin`, `instructor`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `sectionId` | `integer` | βœ… | Section to add schedule to |

#### Request Body

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `dayOfWeek` | `string` | βœ… | `DayOfWeek` enum | Day of week |
| `startTime` | `string` | βœ… | HH:mm format 24-hour (`/^([0-1][0-9]\|2[0-3]):[0-5][0-9]$/`) | Start time |
| `endTime` | `string` | βœ… | HH:mm format (same regex, must be after startTime) | End time |
| `room` | `string` | ❌ | β€” | Room number/name |
| `building` | `string` | ❌ | β€” | Building name |
| `scheduleType` | `string` | βœ… | `ScheduleType` enum | Type of session |

#### Example Request

```json
{
  "dayOfWeek": "MONDAY",
  "startTime": "09:00",
  "endTime": "10:30",
  "room": "A101",
  "building": "Main Building",
  "scheduleType": "LECTURE"
}
```

#### Response `201 Created`

Returns the created schedule object.

#### Error Responses

| Status | Description |
|---|---|
| `400` | Invalid time range (end <= start) or schedule conflict detected |
| `404` | Section not found |

---

### 5.4 Delete Schedule

```
DELETE /api/schedules/:id
```

**Auth Required**: βœ… Yes
**Roles**: `admin`, `it_admin`, `instructor`

#### Response `204 No Content`

Empty body.

---

## 6. Assignments Module

**Base Path**: `/api/assignments`

> **All endpoints require JWT authentication** (`@UseGuards(JwtAuthGuard, RolesGuard)`).

---

### 6.1 List Assignments

```
GET /api/assignments
```

**Auth Required**: βœ… Yes
**Roles**: All authenticated users

#### Query Parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `courseId` | `integer` | ❌ | β€” | Filter by course ID |
| `sectionId` | `integer` | ❌ | β€” | Filter by section ID |
| `status` | `string` | ❌ | β€” | Filter by `AssignmentStatus` enum (`draft`, `published`, `closed`, `archived`) |
| `dueBefore` | `string` | ❌ | β€” | Filter assignments due before this date (ISO 8601) |
| `dueAfter` | `string` | ❌ | β€” | Filter assignments due after this date (ISO 8601) |
| `search` | `string` | ❌ | β€” | Search in assignment title (partial match) |
| `page` | `integer` | ❌ | `1` | Page number |
| `limit` | `integer` | ❌ | `10` | Items per page |
| `sortBy` | `string` | ❌ | `createdAt` | Sort field: `dueDate`, `createdAt`, `title` |
| `sortOrder` | `string` | ❌ | `DESC` | Sort order: `ASC` or `DESC` |

#### Response `200 OK`

```json
{
  "data": [
    {
      "id": 3,                                    // number β€” Assignment ID (bigint)
      "courseId": 1,                               // number β€” FK to courses
      "title": "Homework 1 - Binary Search",       // string β€” Assignment title
      "description": "Implement binary search...",  // string | null
      "instructions": "Submit as .zip file...",     // string | null
      "maxScore": 100.00,                           // number (decimal) β€” Maximum possible score
      "weight": 15.00,                              // number (decimal) β€” Weight % in final grade
      "dueDate": "2025-06-15T23:59:59Z",           // string | null β€” Due date (ISO 8601)
      "availableFrom": "2025-06-01T00:00:00Z",     // string | null β€” Available from date
      "lateSubmissionAllowed": 0,                   // number (0 or 1) β€” 0=false, 1=true
      "latePenaltyPercent": 10.00,                  // number (decimal) β€” Late penalty %
      "submissionType": "file",                     // string β€” SubmissionType enum
      "maxFileSizeMb": 10,                          // number β€” Max file size in MB
      "allowedFileTypes": "[\"pdf\",\"zip\"]",      // string | null β€” JSON string of allowed types
      "status": "published",                        // string β€” AssignmentStatus enum
      "createdBy": 5,                               // number β€” Creator user ID
      "createdAt": "2025-06-01T08:00:00Z",          // string (ISO 8601)
      "updatedAt": "2025-06-01T08:00:00Z",          // string (ISO 8601)
      "course": {                                    // object β€” Joined course info
        "id": 1,
        "departmentId": 3,
        "name": "Introduction to CS",
        "code": "CS101",
        "description": "...",
        "credits": 3,
        "level": "FRESHMAN",
        "status": "ACTIVE"
      }
    }
  ],
  "meta": {
    "total": 12,
    "page": 1,
    "limit": 10,
    "totalPages": 2
  }
}
```

---

### 6.2 Get Assignment Details

```
GET /api/assignments/:id
```

**Auth Required**: βœ… Yes
**Roles**: All authenticated users

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Assignment ID |

#### Response `200 OK`

```json
{
  "id": 3,
  "courseId": 1,
  "title": "Homework 1 - Binary Search",
  "description": "Implement binary search...",
  "instructions": "Submit as .zip file...",
  "maxScore": 100.00,
  "weight": 15.00,
  "dueDate": "2025-06-15T23:59:59Z",
  "availableFrom": "2025-06-01T00:00:00Z",
  "lateSubmissionAllowed": 0,
  "latePenaltyPercent": 10.00,
  "submissionType": "file",
  "maxFileSizeMb": 10,
  "allowedFileTypes": "[\"pdf\",\"zip\"]",
  "status": "published",
  "createdBy": 5,
  "createdAt": "2025-06-01T08:00:00Z",
  "updatedAt": "2025-06-01T08:00:00Z",
  "course": { /* full course object */ },
  "submissions": [
    {
      "id": 1,                             // number β€” Submission ID
      "assignmentId": 3,                   // number
      "userId": 57,                        // number β€” Student user ID
      "submissionText": "My essay...",     // string | null
      "submissionLink": "https://...",     // string | null
      "fileId": 12,                        // number | null β€” FK to files
      "submissionStatus": "submitted",     // string β€” SubmissionStatus enum
      "isLate": 0,                         // number (0 or 1)
      "attemptNumber": 1,                  // number β€” Attempt count
      "submittedAt": "2025-06-10T14:30:00Z",
      "score": null,                       // number | null β€” Graded score
      "feedback": null,                    // string | null β€” Grader feedback
      "gradedBy": null,                    // number | null β€” Grader user ID
      "gradedAt": null,                    // string | null β€” Grading timestamp
      "user": {
        "user_id": 57,
        "first_name": "John",
        "last_name": "Doe",
        "email": "john@example.com"
      }
    }
  ]
}
```

#### Error Responses

| Status | Description |
|---|---|
| `404` | Assignment not found |

---

### 6.3 Create Assignment

```
POST /api/assignments
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `admin`

#### Request Body

| Field | Type | Required | Default | Constraints | Description |
|---|---|---|---|---|---|
| `courseId` | `number` | βœ… | β€” | Must exist | Course ID |
| `title` | `string` | βœ… | β€” | 3-200 chars | Assignment title |
| `description` | `string` | ❌ | `null` | β€” | Description |
| `instructions` | `string` | ❌ | `null` | β€” | Detailed instructions |
| `submissionType` | `string` | ❌ | `file` | `SubmissionType` enum | How students submit |
| `maxScore` | `number` | ❌ | `100` | 0-1000 | Maximum score |
| `weight` | `number` | ❌ | `0` | 0-100 | Weight percentage in final grade |
| `dueDate` | `string` | ❌ | `null` | ISO 8601 datetime | Due date |
| `availableFrom` | `string` | ❌ | `null` | ISO 8601 datetime | Available from date |
| `lateSubmissionAllowed` | `boolean` | ❌ | `false` | β€” | Allow late submissions |
| `latePenaltyPercent` | `number` | ❌ | `0` | 0-100 | Late penalty % |
| `maxFileSizeMb` | `number` | ❌ | `10` | β€” | Max file size in MB |
| `allowedFileTypes` | `string` | ❌ | `null` | JSON string array | Allowed file extensions |
| `status` | `string` | ❌ | `draft` | `AssignmentStatus` enum | Initial status |

#### Example Request

```json
{
  "courseId": 1,
  "title": "Homework 1 - Binary Search",
  "description": "Implement a binary search tree with insert, delete, and search operations.",
  "instructions": "Submit your code as a single .zip file. Include a README with compilation instructions.",
  "submissionType": "file",
  "maxScore": 100,
  "weight": 15,
  "dueDate": "2025-06-15T23:59:59Z",
  "availableFrom": "2025-06-01T00:00:00Z",
  "lateSubmissionAllowed": true,
  "latePenaltyPercent": 10,
  "maxFileSizeMb": 10,
  "allowedFileTypes": "[\"pdf\",\"docx\",\"zip\"]",
  "status": "draft"
}
```

#### Response `201 Created`

Returns the created assignment with joined `course` relation.

---

### 6.4 Update Assignment

```
PATCH /api/assignments/:id
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `admin`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Assignment ID |

#### Request Body

All fields from `CreateAssignmentDto` are **optional** (uses `PartialType`).

#### Response `200 OK`

Returns the updated assignment object.

---

### 6.5 Delete Assignment (Soft Delete)

```
DELETE /api/assignments/:id
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `admin`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Assignment ID |

#### Response `200 OK`

Empty body (assignment removed).

---

### 6.6 Change Assignment Status

```
PATCH /api/assignments/:id/status
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `admin`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Assignment ID |

#### Request Body

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `status` | `string` | βœ… | Must follow: `draft` -> `published` -> `closed` -> `archived` | New status |

> **WARNING β€” Transition rules**: Only the next status in the chain is allowed. You cannot skip statuses. E.g., you cannot go from `draft` directly to `closed`.

#### Example Request

```json
{
  "status": "published"
}
```

#### Response `200 OK`

Returns the updated assignment object.

#### Error Responses

| Status | Description |
|---|---|
| `400` | Invalid status transition |
| `404` | Assignment not found |

---

### 6.7 Submit Assignment (Student)

```
POST /api/assignments/:id/submit
```

**Auth Required**: βœ… Yes
**Roles**: `student` only

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Assignment ID |

#### Request Body

| Field | Type | Required | Description |
|---|---|---|---|
| `submissionText` | `string` | ❌ | Text content for text submissions |
| `fileId` | `number` | ❌ | File ID from the files module (for file submissions) |
| `submissionLink` | `string` | ❌ | External URL (e.g., GitHub repo link) |

> At least one of `submissionText`, `fileId`, or `submissionLink` should be provided.

#### Example Request

```json
{
  "submissionText": "This is my essay submission about data structures...",
  "submissionLink": "https://github.com/student/project"
}
```

#### Response `201 Created` (via POST)

```json
{
  "id": 15,                               // number β€” Submission ID
  "assignmentId": 3,                      // number
  "userId": 57,                           // number β€” From JWT
  "submissionText": "This is my essay...",
  "submissionLink": "https://github.com/student/project",
  "fileId": null,
  "submissionStatus": "submitted",
  "isLate": 0,                            // number β€” 0=on-time, 1=late
  "attemptNumber": 1,                     // number β€” Auto-incremented
  "submittedAt": "2025-06-10T14:30:00Z",
  "score": null,
  "feedback": null,
  "gradedBy": null,
  "gradedAt": null
}
```

#### Error Responses

| Status | Description |
|---|---|
| `400` | Student not enrolled in course / Late submission not allowed / Assignment not available yet |
| `404` | Assignment not found |

#### Business Rules
- Assignment must be in `published` status
- If `availableFrom` is set, current time must be after it
- If `dueDate` is set and past, `lateSubmissionAllowed` must be `true` (otherwise 400)
- Auto-marks `isLate = 1` if submitted after `dueDate`
- Auto-increments `attemptNumber`
- Student must be enrolled in the assignment's course

---

### 6.8 Get My Submission (Student)

```
GET /api/assignments/:id/submissions/my
```

**Auth Required**: βœ… Yes
**Roles**: `student` only

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Assignment ID |

#### Response `200 OK`

Returns the student's **latest** submission (highest `attemptNumber`):

```json
{
  "id": 15,
  "assignmentId": 3,
  "userId": 57,
  "submissionText": "My submission...",
  "submissionLink": null,
  "fileId": 12,
  "submissionStatus": "graded",
  "isLate": 0,
  "attemptNumber": 2,
  "submittedAt": "2025-06-10T14:30:00Z",
  "score": 85.00,
  "feedback": "Well done! Consider improving error handling.",
  "gradedBy": 5,
  "gradedAt": "2025-06-12T10:00:00Z"
}
```

#### Error Responses

| Status | Description |
|---|---|
| `404` | No submission found for this student/assignment |

---

### 6.9 List All Submissions (Instructor/TA/Admin)

```
GET /api/assignments/:id/submissions
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Assignment ID |

#### Response `200 OK`

```json
[
  {
    "id": 15,
    "assignmentId": 3,
    "userId": 57,
    "submissionText": "My submission...",
    "submissionLink": null,
    "fileId": 12,
    "submissionStatus": "submitted",
    "isLate": 0,
    "attemptNumber": 1,
    "submittedAt": "2025-06-10T14:30:00Z",
    "score": null,
    "feedback": null,
    "gradedBy": null,
    "gradedAt": null,
    "user": {
      "user_id": 57,
      "first_name": "John",
      "last_name": "Doe",
      "email": "john@example.com"
    }
  }
]
```

> Returns submissions sorted by `submittedAt` DESC.

---

### 6.10 Grade a Submission

```
PATCH /api/assignments/:id/submissions/:subId/grade
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Assignment ID |
| `subId` | `integer` | βœ… | Submission ID |

#### Request Body

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `score` | `number` | βœ… | >= 0 | Numeric score |
| `feedback` | `string` | ❌ | β€” | Feedback comments |

#### Example Request

```json
{
  "score": 85,
  "feedback": "Well done! Consider improving the conclusion."
}
```

#### Response `200 OK`

```json
{
  "submissionId": 15,        // number β€” Graded submission ID
  "score": 85,               // number β€” Score assigned
  "maxScore": 100,           // number β€” Assignment max score
  "feedback": "Well done!",  // string | undefined
  "gradeId": 42              // number β€” Created grade record ID in central gradebook
}
```

> **Side effect**: Also creates a grade record in the central `grades` table with `gradeType = 'assignment'`, `isPublished = true`.

---

### 6.11 Upload Assignment Instruction (Google Drive)

```
POST /api/assignments/:id/instructions/upload
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`
**Content-Type**: `multipart/form-data`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Assignment ID |

#### Form Data Fields

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `file` | `binary` | βœ… | PDF, DOCX, etc. | The instruction file |
| `title` | `string` | ❌ | Max 255 chars | Instruction title |
| `orderIndex` | `integer` | ❌ | >= 0, default `0` | Sort order |

#### Response `201 Created`

```json
{
  "assignmentId": 3,
  "driveFile": {
    "driveFileId": 123,           // number β€” Internal drive file record ID
    "driveId": "1abc...",          // string β€” Google Drive file ID
    "fileName": "HW1_Instructions_v1.pdf",
    "webViewLink": "https://drive.google.com/file/d/1abc.../view",
    "webContentLink": "https://drive.google.com/uc?id=1abc..."
  }
}
```

---

### 6.12 Upload Assignment Submission (Google Drive β€” Student)

```
POST /api/assignments/:id/submissions/upload
```

**Auth Required**: βœ… Yes
**Roles**: `student` only
**Content-Type**: `multipart/form-data`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Assignment ID |

#### Form Data Fields

| Field | Type | Required | Description |
|---|---|---|---|
| `file` | `binary` | βœ… | Submission file |
| `submissionText` | `string` | ❌ | Notes/comments |
| `submissionLink` | `string` | ❌ | External link (e.g., GitHub) |

#### Response `201 Created`

```json
{
  "submission": {
    "id": 16,
    "assignmentId": 3,
    "userId": 57,
    "submissionText": "Completed all tasks.",
    "submissionLink": "https://github.com/student/project",
    "fileId": null,
    "submissionStatus": "submitted",
    "isLate": 0,
    "attemptNumber": 1,
    "submittedAt": "2025-06-10T14:30:00Z",
    "score": null,
    "feedback": null,
    "gradedBy": null,
    "gradedAt": null
  },
  "driveFile": {
    "driveFileId": 124,
    "driveId": "1def...",
    "fileName": "Assignment_3_Submission_20250610.zip",
    "webViewLink": "https://drive.google.com/file/d/1def.../view",
    "webContentLink": "https://drive.google.com/uc?id=1def..."
  },
  "isLate": false                // boolean β€” Whether submission was late
}
```

#### Business Rules

Same as regular submit (section 6.7): must be published, enrolled, respects late submission rules.

---

## 7. Labs Module

**Base Path**: `/api/labs`

> **All endpoints require JWT authentication** (`@UseGuards(JwtAuthGuard, RolesGuard)`).

---

### 7.1 List Labs

```
GET /api/labs
```

**Auth Required**: βœ… Yes
**Roles**: All authenticated users

#### Query Parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `courseId` | `integer` | ❌ | β€” | Filter by course ID |
| `status` | `string` | ❌ | β€” | Filter by `LabStatus` enum (`draft`, `published`, `closed`, `archived`) |
| `page` | `integer` | ❌ | `1` | Page number (>= 1) |
| `limit` | `integer` | ❌ | `20` | Items per page (1-100) |

#### Response `200 OK`

```json
{
  "data": [
    {
      "id": 1,                              // number β€” Lab ID (bigint)
      "courseId": 1,                         // number β€” FK to courses
      "title": "Binary Search Lab",          // string β€” Lab title
      "description": "Implement binary...",  // string | null
      "labNumber": 1,                        // number | null β€” Lab sequence number
      "dueDate": "2026-04-15T23:59:59Z",    // string | null β€” Due date (ISO 8601)
      "availableFrom": "2026-04-01T00:00:00Z", // string | null
      "maxScore": 100.00,                    // number (decimal) β€” Max score
      "weight": 10.00,                       // number (decimal) β€” Weight in final grade
      "status": "published",                 // string β€” LabStatus enum
      "createdBy": 5,                        // number β€” Creator user ID
      "createdAt": "2026-04-01T08:00:00Z",
      "updatedAt": "2026-04-01T08:00:00Z",
      "course": {
        "id": 1,
        "departmentId": 3,
        "name": "Introduction to CS",
        "code": "CS101"
      }
    }
  ],
  "meta": {
    "total": 8,
    "page": 1,
    "limit": 20,
    "totalPages": 1
  }
}
```

---

### 7.2 Get Lab by ID

```
GET /api/labs/:id
```

**Auth Required**: βœ… Yes
**Roles**: All authenticated users

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Lab ID |

#### Response `200 OK`

```json
{
  "id": 1,
  "courseId": 1,
  "title": "Binary Search Lab",
  "description": "Implement binary search in Python",
  "labNumber": 1,
  "dueDate": "2026-04-15T23:59:59Z",
  "availableFrom": "2026-04-01T00:00:00Z",
  "maxScore": 100.00,
  "weight": 10.00,
  "status": "published",
  "createdBy": 5,
  "createdAt": "2026-04-01T08:00:00Z",
  "updatedAt": "2026-04-01T08:00:00Z",
  "course": { /* course object */ },
  "instructions": [
    {
      "id": 1,                          // number β€” Instruction ID
      "labId": 1,                       // number
      "fileId": null,                   // number | null β€” FK to files
      "instructionText": "Step 1: Create a new Python file",  // string | null
      "orderIndex": 1,                  // number β€” Sort order
      "createdAt": "2026-04-01T08:00:00Z"
    }
  ]
}
```

---

### 7.3 Create Lab

```
POST /api/labs
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`, `it_admin`

#### Request Body

| Field | Type | Required | Default | Constraints | Description |
|---|---|---|---|---|---|
| `courseId` | `integer` | βœ… | β€” | Must exist | Course ID |
| `title` | `string` | βœ… | β€” | β€” | Lab title |
| `description` | `string` | ❌ | `null` | β€” | Lab description |
| `labNumber` | `integer` | ❌ | `null` | β€” | Lab sequence number |
| `dueDate` | `string` | ❌ | `null` | ISO 8601 | Due date |
| `availableFrom` | `string` | ❌ | `null` | ISO 8601 | Available from date |
| `maxScore` | `number` | ❌ | `100` | β€” | Maximum score |
| `weight` | `number` | ❌ | `0` | β€” | Weight in final grade |
| `status` | `string` | ❌ | `draft` | `LabStatus` enum | Initial status |

#### Example Request

```json
{
  "courseId": 1,
  "title": "Binary Search Lab",
  "description": "Implement binary search in Python",
  "labNumber": 1,
  "dueDate": "2026-04-15T23:59:59Z",
  "availableFrom": "2026-04-01T00:00:00Z",
  "maxScore": 100,
  "weight": 10,
  "status": "draft"
}
```

#### Response `201 Created`

Returns the created lab object.

---

### 7.4 Update Lab

```
PUT /api/labs/:id
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`, `it_admin`

> **Note**: This endpoint uses **PUT** (full replacement), but since `UpdateLabDto extends PartialType(CreateLabDto)`, all fields are optional.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Lab ID |

#### Request Body

All fields from `CreateLabDto` are **optional** (uses `PartialType`).

#### Response `200 OK`

Returns the updated lab object.

---

### 7.5 Delete Lab

```
DELETE /api/labs/:id
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `admin`, `it_admin`

> **Note**: TAs **cannot** delete labs.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Lab ID |

#### Response `204 No Content`

Empty body.

---

### 7.6 Change Lab Status

```
PATCH /api/labs/:id/status
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`, `it_admin`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Lab ID |

#### Request Body

| Field | Type | Required | Description |
|---|---|---|---|
| `status` | `string` | βœ… | One of: `draft`, `published`, `closed`, `archived` |

> **Note**: Unlike assignments, lab status changes do **not** enforce strict one-way transitions. Any valid status value can be set.

#### Response `200 OK`

Returns the updated lab object (full Lab entity with relations).

---

### 7.7 Get Lab Instructions

```
GET /api/labs/:id/instructions
```

**Auth Required**: βœ… Yes
**Roles**: All authenticated users

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Lab ID |

#### Response `200 OK`

```json
[
  {
    "id": 1,                        // number β€” Instruction ID
    "labId": 1,                     // number β€” FK to labs
    "fileId": null,                 // number | null β€” FK to files table
    "instructionText": "Step 1...", // string | null β€” Markdown text
    "orderIndex": 1,                // number β€” Sort order (ascending)
    "createdAt": "2026-04-01T08:00:00Z"
  },
  {
    "id": 2,
    "labId": 1,
    "fileId": 5,
    "instructionText": "See attached PDF",
    "orderIndex": 2,
    "createdAt": "2026-04-01T08:05:00Z"
  }
]
```

---

### 7.8 Add Instruction to Lab

```
POST /api/labs/:id/instructions
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`, `it_admin`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Lab ID |

#### Request Body

| Field | Type | Required | Default | Description |
|---|---|---|---|---|
| `instructionText` | `string` | ❌ | `null` | Instruction content (supports markdown) |
| `fileId` | `integer` | ❌ | `null` | FK to files table for attachment |
| `orderIndex` | `integer` | ❌ | `0` | Sort order |

#### Example Request

```json
{
  "instructionText": "Step 1: Create a new Python file called `binary_search.py`",
  "orderIndex": 1
}
```

#### Response `201 Created`

Returns the created instruction object.

---

### 7.9 Submit Lab Work (Student)

```
POST /api/labs/:id/submit
```

**Auth Required**: βœ… Yes
**Roles**: `student` only

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Lab ID |

#### Request Body

| Field | Type | Required | Description |
|---|---|---|---|
| `submissionText` | `string` | ❌ | Text/code submission content |
| `fileId` | `integer` | ❌ | File ID from files module |

#### Example Request

```json
{
  "submissionText": "def binary_search(arr, target):\n    ...",
  "fileId": 10
}
```

#### Response `201 Created`

```json
{
  "id": 5,                           // number β€” Submission ID
  "labId": 1,                        // number
  "userId": 57,                      // number β€” From JWT
  "submissionText": "def binary...",  // string | null
  "fileId": 10,                      // number | null
  "submittedAt": "2026-04-10T14:30:00Z",
  "isLate": false,                   // boolean β€” Auto-detected
  "status": "submitted",             // string β€” LabSubmissionStatus
  "score": null,                     // number | null
  "feedback": null,                  // string | null
  "gradedBy": null,                  // number | null
  "gradedAt": null                   // string | null
}
```

#### Business Rules
- Auto-detects late submission based on `lab.dueDate`
- Sets `isLate = true` if current time > dueDate

---

### 7.10 List Lab Submissions (Instructor/TA/Admin)

```
GET /api/labs/:id/submissions
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`, `it_admin`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Lab ID |

#### Response `200 OK`

```json
[
  {
    "id": 5,
    "labId": 1,
    "userId": 57,
    "submissionText": "My solution...",
    "fileId": 10,
    "submittedAt": "2026-04-10T14:30:00Z",
    "isLate": false,
    "status": "submitted",
    "score": null,
    "feedback": null,
    "gradedBy": null,
    "gradedAt": null,
    "user": {
      "user_id": 57,
      "first_name": "John",
      "last_name": "Doe",
      "email": "john@example.com"
    },
    "file": {
      "file_id": 10,
      "file_name": "solution.py",
      "file_path": "/uploads/...",
      "mime_type": "text/x-python"
    }
  }
]
```

> Sorted by `submittedAt` DESC.

---

### 7.11 Get My Lab Submission (Student)

```
GET /api/labs/:id/submissions/my
```

**Auth Required**: βœ… Yes
**Roles**: `student` only

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Lab ID |

#### Response `200 OK`

Returns an **array** of the student's submissions for this lab (may have multiple), sorted by `submittedAt` DESC. Includes `user` and `file` relations.

```json
[
  {
    "id": 5,
    "labId": 1,
    "userId": 57,
    "submissionText": "...",
    "fileId": 10,
    "submittedAt": "2026-04-10T14:30:00Z",
    "isLate": false,
    "status": "graded",
    "score": 90.00,
    "feedback": "Great work!",
    "gradedBy": 5,
    "gradedAt": "2026-04-12T10:00:00Z",
    "user": { /* student info */ },
    "file": { /* file info or null */ }
  }
]
```

> **Note**: Unlike assignments (which returns the latest single submission), labs returns **all** submissions as an array.

---

### 7.12 Grade Lab Submission

```
PATCH /api/labs/:id/submissions/:subId/grade
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`, `it_admin`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Lab ID |
| `subId` | `integer` | βœ… | Submission ID |

#### Request Body

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `status` | `string` | βœ… | One of: `submitted`, `graded`, `returned`, `resubmit` | Submission status |
| `score` | `number` | ❌ | >= 0 | Score to assign |
| `feedback` | `string` | ❌ | β€” | Feedback for student |

#### Example Request

```json
{
  "status": "graded",
  "score": 85,
  "feedback": "Good work! Consider optimizing your code for better performance."
}
```

#### Response `200 OK`

Returns the updated submission object with `user`, `file`, and `grader` relations:

```json
{
  "id": 5,
  "labId": 1,
  "userId": 57,
  "submissionText": "...",
  "fileId": 10,
  "submittedAt": "2026-04-10T14:30:00Z",
  "isLate": false,
  "status": "graded",
  "score": 85.00,
  "feedback": "Good work!...",
  "gradedBy": 5,
  "gradedAt": "2026-04-12T10:00:00Z",
  "user": { /* student info */ },
  "file": { /* file info or null */ },
  "grader": {
    "user_id": 5,
    "first_name": "Prof. Smith",
    "last_name": "Smith",
    "email": "smith@example.com"
  }
}
```

> **Side effect**: When `status = 'graded'` and `score` is provided, automatically creates a grade record in the central `grades` table with `gradeType = 'lab'`, `isPublished = true`.

---

### 7.13 Mark Lab Attendance

```
POST /api/labs/:id/attendance
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`, `it_admin`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Lab ID |

#### Request Body

| Field | Type | Required | Description |
|---|---|---|---|
| `userId` | `integer` | βœ… | Student user ID to mark |
| `attendanceStatus` | `string` | βœ… | One of: `present`, `absent`, `excused`, `late` |
| `notes` | `string` | ❌ | Additional notes |

#### Example Request

```json
{
  "userId": 57,
  "attendanceStatus": "present",
  "notes": "Arrived on time"
}
```

#### Response `201 Created`

```json
{
  "id": 10,                          // number β€” Attendance record ID
  "labId": 1,                        // number
  "userId": 57,                      // number
  "attendanceStatus": "present",     // string β€” LabAttendanceStatus
  "checkInTime": "2026-04-10T09:00:00Z",  // string | null β€” Auto-set for present/late
  "notes": "Arrived on time",        // string | null
  "markedBy": 5,                     // number β€” User who marked (from JWT)
  "createdAt": "2026-04-10T09:00:00Z"
}
```

#### Business Rules
- If a record already exists for this student+lab, it **updates** the existing record
- `checkInTime` is automatically set when status is `present` or `late`

---

### 7.14 Get Lab Attendance

```
GET /api/labs/:id/attendance
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`, `it_admin`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Lab ID |

#### Response `200 OK`

```json
[
  {
    "id": 10,
    "labId": 1,
    "userId": 57,
    "attendanceStatus": "present",
    "checkInTime": "2026-04-10T09:00:00Z",
    "notes": "Arrived on time",
    "markedBy": 5,
    "createdAt": "2026-04-10T09:00:00Z"
  }
]
```

> Sorted by `createdAt` ASC.

---

### 7.15 Upload Lab Instruction (Google Drive)

```
POST /api/labs/:id/instructions/upload
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`, `it_admin`
**Content-Type**: `multipart/form-data`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Lab ID |

#### Form Data Fields

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `file` | `binary` | βœ… | PDF, DOCX, etc. | Instruction file |
| `title` | `string` | ❌ | Max 255 chars | Instruction title |
| `orderIndex` | `integer` | ❌ | >= 0, default `0` | Sort order |

#### Response `201 Created`

```json
{
  "instruction": {
    "id": 3,
    "labId": 1,
    "instructionText": "Lab 1 - Getting Started Guide",
    "orderIndex": 1,
    "createdAt": "2026-04-01T08:00:00Z"
  },
  "driveFile": {
    "driveId": "1abc...",
    "fileName": "Lab_1_-_Getting_Started_Guide_v1.pdf",
    "webViewLink": "https://drive.google.com/file/d/1abc.../view",
    "webContentLink": "https://drive.google.com/uc?id=1abc..."
  }
}
```

---

### 7.16 Upload TA Material (Google Drive)

```
POST /api/labs/:id/ta-materials/upload
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`, `it_admin`
**Content-Type**: `multipart/form-data`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Lab ID |

#### Form Data Fields

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `file` | `binary` | βœ… | β€” | TA material file |
| `title` | `string` | ❌ | Max 255 chars | Material title |
| `materialType` | `string` | ❌ | One of: `answer_key`, `grading_rubric`, `solution`, `notes` | Type of TA material |

#### Response `201 Created`

```json
{
  "driveFile": {
    "driveFileId": 125,
    "driveId": "1ghi...",
    "fileName": "solution_Lab_1_Answer_Key.pdf",
    "webViewLink": "https://drive.google.com/file/d/1ghi.../view",
    "webContentLink": "https://drive.google.com/uc?id=1ghi..."
  }
}
```

---

### 7.17 Upload Lab Submission (Google Drive β€” Student)

```
POST /api/labs/:id/submissions/upload
```

**Auth Required**: βœ… Yes
**Roles**: `student` only
**Content-Type**: `multipart/form-data`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Lab ID |

#### Form Data Fields

| Field | Type | Required | Description |
|---|---|---|---|
| `file` | `binary` | βœ… | Submission file |
| `submissionText` | `string` | ❌ | Notes/comments |

#### Response `201 Created`

```json
{
  "submission": {
    "id": 6,
    "labId": 1,
    "userId": 57,
    "submissionText": "My implementation uses iterative approach",
    "submittedAt": "2026-04-10T14:30:00Z",
    "isLate": false,
    "status": "submitted",
    "score": null,
    "feedback": null,
    "gradedBy": null,
    "gradedAt": null
  },
  "driveFile": {
    "driveFileId": 126,
    "driveId": "1jkl...",
    "fileName": "Lab1_Submission_20260410.py",
    "webViewLink": "https://drive.google.com/file/d/1jkl.../view",
    "webContentLink": "https://drive.google.com/uc?id=1jkl..."
  },
  "isLate": false
}
```

#### Business Rules
- If a submission already exists for this student+lab, the existing record is **updated** (not duplicated)
- Auto-detects `isLate` based on `lab.dueDate`

---

## 8. Role-Based Access Matrix

### 8.1 Courses

| Endpoint | Student | Instructor | TA | Admin | IT Admin | Dept Head |
|---|:---:|:---:|:---:|:---:|:---:|:---:|
| `GET /api/courses` (list) | βœ… Public | βœ… Public | βœ… Public | βœ… Public | βœ… Public | βœ… Public |
| `GET /api/courses/:id` (details) | βœ… Public | βœ… Public | βœ… Public | βœ… Public | βœ… Public | βœ… Public |
| `GET /api/courses/department/:deptId` | βœ… Public | βœ… Public | βœ… Public | βœ… Public | βœ… Public | βœ… Public |
| `POST /api/courses` (create) | ❌ | βœ… | ❌ | βœ… | βœ… | ❌ |
| `PATCH /api/courses/:id` (update) | ❌ | βœ… | ❌ | βœ… | βœ… | ❌ |
| `DELETE /api/courses/:id` (delete) | ❌ | ❌ | ❌ | βœ… | βœ… | ❌ |
| `GET /api/courses/:id/prerequisites` | βœ… Public | βœ… Public | βœ… Public | βœ… Public | βœ… Public | βœ… Public |
| `POST /api/courses/:id/prerequisites` | ❌ | ❌ | ❌ | βœ… | βœ… | ❌ |
| `DELETE /api/courses/:id/prerequisites/:id` | ❌ | ❌ | ❌ | βœ… | βœ… | ❌ |

### 8.2 Course Sections

| Endpoint | Student | Instructor | TA | Admin | IT Admin | Dept Head |
|---|:---:|:---:|:---:|:---:|:---:|:---:|
| `GET /api/sections/course/:courseId` | βœ… Public | βœ… Public | βœ… Public | βœ… Public | βœ… Public | βœ… Public |
| `GET /api/sections/:id` | βœ… Public | βœ… Public | βœ… Public | βœ… Public | βœ… Public | βœ… Public |
| `POST /api/sections` (create) | ❌ | βœ… | ❌ | βœ… | βœ… | ❌ |
| `PATCH /api/sections/:id` (update) | ❌ | βœ… | ❌ | βœ… | βœ… | ❌ |
| `PATCH /api/sections/:id/enrollment` | ❌ | βœ… | ❌ | βœ… | βœ… | ❌ |

### 8.3 Course Schedules

| Endpoint | Student | Instructor | TA | Admin | IT Admin | Dept Head |
|---|:---:|:---:|:---:|:---:|:---:|:---:|
| `GET /api/schedules/section/:sectionId` | βœ… Public | βœ… Public | βœ… Public | βœ… Public | βœ… Public | βœ… Public |
| `GET /api/schedules/:id` | βœ… Public | βœ… Public | βœ… Public | βœ… Public | βœ… Public | βœ… Public |
| `POST /api/schedules/section/:sectionId` | ❌ | βœ… | ❌ | βœ… | βœ… | ❌ |
| `DELETE /api/schedules/:id` | ❌ | βœ… | ❌ | βœ… | βœ… | ❌ |

### 8.4 Assignments

| Endpoint | Student | Instructor | TA | Admin | IT Admin | Dept Head |
|---|:---:|:---:|:---:|:---:|:---:|:---:|
| `GET /api/assignments` (list) | βœ… | βœ… | βœ… | βœ… | βœ… | ❌ |
| `GET /api/assignments/:id` (details) | βœ… | βœ… | βœ… | βœ… | βœ… | ❌ |
| `POST /api/assignments` (create) | ❌ | βœ… | βœ… | βœ… | ❌ | ❌ |
| `PATCH /api/assignments/:id` (update) | ❌ | βœ… | βœ… | βœ… | ❌ | ❌ |
| `DELETE /api/assignments/:id` (delete) | ❌ | βœ… | βœ… | βœ… | ❌ | ❌ |
| `PATCH /api/assignments/:id/status` | ❌ | βœ… | βœ… | βœ… | ❌ | ❌ |
| `POST /api/assignments/:id/submit` | βœ… | ❌ | ❌ | ❌ | ❌ | ❌ |
| `GET /api/assignments/:id/submissions/my` | βœ… | ❌ | ❌ | ❌ | ❌ | ❌ |
| `GET /api/assignments/:id/submissions` | ❌ | βœ… | βœ… | βœ… | ❌ | ❌ |
| `PATCH /:id/submissions/:subId/grade` | ❌ | βœ… | βœ… | ❌ | ❌ | ❌ |
| `POST /:id/instructions/upload` | ❌ | βœ… | βœ… | βœ… | ❌ | ❌ |
| `POST /:id/submissions/upload` | βœ… | ❌ | ❌ | ❌ | ❌ | ❌ |

### 8.5 Labs

| Endpoint | Student | Instructor | TA | Admin | IT Admin | Dept Head |
|---|:---:|:---:|:---:|:---:|:---:|:---:|
| `GET /api/labs` (list) | βœ… | βœ… | βœ… | βœ… | βœ… | ❌ |
| `GET /api/labs/:id` (details) | βœ… | βœ… | βœ… | βœ… | βœ… | ❌ |
| `POST /api/labs` (create) | ❌ | βœ… | βœ… | βœ… | βœ… | ❌ |
| `PUT /api/labs/:id` (update) | ❌ | βœ… | βœ… | βœ… | βœ… | ❌ |
| `DELETE /api/labs/:id` (delete) | ❌ | βœ… | βœ… | βœ… | βœ… | ❌ |
| `PATCH /api/labs/:id/status` | ❌ | βœ… | βœ… | βœ… | βœ… | ❌ |
| `GET /api/labs/:id/instructions` | βœ… | βœ… | βœ… | βœ… | βœ… | ❌ |
| `POST /api/labs/:id/instructions` | ❌ | βœ… | βœ… | βœ… | βœ… | ❌ |
| `POST /api/labs/:id/submit` | βœ… | ❌ | ❌ | ❌ | ❌ | ❌ |
| `GET /api/labs/:id/submissions` | ❌ | βœ… | βœ… | βœ… | βœ… | ❌ |
| `GET /api/labs/:id/submissions/my` | βœ… | ❌ | ❌ | ❌ | ❌ | ❌ |
| `PATCH /:id/submissions/:subId/grade` | ❌ | βœ… | βœ… | βœ… | βœ… | ❌ |
| `POST /api/labs/:id/attendance` | ❌ | βœ… | βœ… | βœ… | βœ… | ❌ |
| `GET /api/labs/:id/attendance` | ❌ | βœ… | βœ… | βœ… | βœ… | ❌ |
| `POST /:id/instructions/upload` | ❌ | βœ… | βœ… | βœ… | βœ… | ❌ |
| `POST /:id/ta-materials/upload` | ❌ | βœ… | βœ… | βœ… | βœ… | ❌ |
| `POST /:id/submissions/upload` | βœ… | ❌ | ❌ | ❌ | ❌ | ❌ |

### 8.6 Enrollments

| Endpoint | Student | Instructor | TA | Admin | IT Admin | Dept Head |
|---|:---:|:---:|:---:|:---:|:---:|:---:|
| `GET /api/enrollments/my-courses` | βœ… | ❌ | ❌ | ❌ | ❌ | ❌ |
| `GET /api/enrollments/available` | βœ… | ❌ | ❌ | ❌ | ❌ | ❌ |
| `POST /api/enrollments/register` | βœ… | ❌ | ❌ | ❌ | ❌ | ❌ |
| `DELETE /api/enrollments/:id` | βœ… | ❌ | ❌ | βœ… | ❌ | ❌ |
| `GET /api/enrollments/teaching` | ❌ | βœ… | βœ… | βœ… | ❌ | ❌ |
| `GET /api/enrollments/periods` | βœ… | βœ… | βœ… | βœ… | βœ… | βœ… |
| `GET /api/sections/:sectionId/students` | ❌ | βœ… | βœ… | βœ… | ❌ | ❌ |
| `GET /api/sections/:sectionId/waitlist` | ❌ | βœ… | ❌ | βœ… | ❌ | ❌ |
| `POST /api/enrollments/sections/:sectionId/instructors` | ❌ | ❌ | ❌ | βœ… | ❌ | ❌ |
| `DELETE /api/enrollments/sections/:sectionId/instructors/:id` | ❌ | ❌ | ❌ | βœ… | ❌ | ❌ |
| `GET /api/enrollments/sections/:sectionId/instructors` | ❌ | βœ… | βœ… | βœ… | ❌ | ❌ |
| `POST /api/enrollments/sections/:sectionId/tas` | ❌ | ❌ | ❌ | βœ… | ❌ | ❌ |
| `DELETE /api/enrollments/sections/:sectionId/tas/:id` | ❌ | ❌ | ❌ | βœ… | ❌ | ❌ |
| `GET /api/enrollments/sections/:sectionId/tas` | ❌ | βœ… | βœ… | βœ… | ❌ | ❌ |

> **Note**: `department_head` role currently has **NO access** to courses/assignments/labs features. This role only has access to schedule templates and campus events.

---

## 9. Course Enrollment Module

**Base Path**: `/api/enrollments`

> **All endpoints require JWT authentication** (`@UseGuards(JwtAuthGuard, RolesGuard)`).
> This module handles student enrollment in courses, including registration, dropping, available courses with prerequisites validation, and instructor/TA assignment to sections.

### 9.0 Enrollment Enums

#### EnrollmentStatus
| Value | Description |
|---|---|
| `enrolled` | Student is actively enrolled in the section |
| `waitlisted` | Student is on the waitlist (not currently implemented) |
| `dropped` | Student has dropped/withdrawn from the section |
| `completed` | Student has completed the course with a grade |
| `failed` | Student failed the course |

#### DropReason
| Value | Description |
|---|---|
| `student_request` | Student voluntarily dropped |
| `administrative` | Admin-initiated drop |
| `academic` | Academic reasons (e.g., failed prerequisite) |
| `schedule_conflict` | Schedule conflict detected |

### 9.0.1 Database Entity

#### `course_enrollments` Table

| Column | DB Type | TS Type | Nullable | Default | Description |
|---|---|---|---|---|---|
| `enrollment_id` | `bigint unsigned` | `number` | ❌ (PK) | Auto | Primary key |
| `user_id` | `bigint unsigned` | `number` | ❌ | β€” | FK β†’ `users` (student) |
| `section_id` | `bigint unsigned` | `number` | ❌ | β€” | FK β†’ `course_sections` |
| `program_id` | `bigint unsigned` | `number \| null` | βœ… | `null` | FK β†’ `programs` |
| `enrollment_status` | `enum('enrolled','waitlisted','dropped','completed','failed')` | `EnrollmentStatus` | ❌ | `'enrolled'` | Enrollment status |
| `grade` | `varchar(5)` | `string \| null` | βœ… | `null` | Letter grade (A, A-, B+, etc.) |
| `final_score` | `decimal(5,2)` | `number \| null` | βœ… | `null` | Final numeric score |
| `enrollment_date` | `datetime` | `Date` | ❌ | Auto | When student enrolled |
| `dropped_at` | `datetime` | `Date \| null` | βœ… | `null` | When student dropped |
| `completed_at` | `datetime` | `Date \| null` | βœ… | `null` | When course was completed |
| `updated_at` | `timestamp` | `Date` | ❌ | Auto | Last update timestamp |

**Indexes**: `(user_id, status)`, `(section_id, status)`, unique constraint on `(user_id, section_id)`

---

### 9.1 Get My Enrolled Courses (Student)

```
GET /api/enrollments/my-courses
```

**Auth Required**: βœ… Yes
**Roles**: `student` only

#### Query Parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `semester` | `integer` | ❌ | β€” | Filter by semester ID |

#### Response `200 OK`

```json
[
  {
    "id": 1,                                // number β€” Enrollment ID
    "userId": 57,                            // number β€” Student user ID
    "sectionId": 11,                          // number β€” Section ID
    "status": "enrolled",                     // string β€” EnrollmentStatus enum
    "grade": null,                           // string | null β€” Letter grade
    "finalScore": null,                      // number | null β€” Final numeric score
    "enrollmentDate": "2025-09-01T10:00:00Z", // string β€” ISO 8601
    "droppedAt": null,                       // string | null
    "completedAt": null,                     // string | null
    "updatedAt": "2025-09-01T10:00:00Z",     // string β€” ISO 8601
    "canDrop": true,                         // boolean β€” Whether student can still drop
    "dropDeadline": "2025-10-15T23:59:59Z",  // string | null β€” Drop deadline
    "course": {
      "id": 1,
      "name": "Introduction to CS",
      "code": "CS101",
      "description": "...",
      "credits": 3,
      "level": "FRESHMAN"
    },
    "section": {
      "id": 11,
      "sectionNumber": "1",
      "maxCapacity": 30,
      "currentEnrollment": 25,
      "location": "Room A101",
      "status": "OPEN"
    },
    "semester": {
      "id": 1,
      "name": "Fall 2025",
      "startDate": "2025-09-01",
      "endDate": "2025-12-15"
    },
    "instructor": null,                      // object | null β€” Currently disabled
    "prerequisites": [                       // array β€” Prerequisites with completion status
      {
        "id": 1,
        "courseId": 1,
        "prerequisiteCourseId": 2,
        "courseCode": "CS100",
        "courseName": "Programming Basics",
        "isMandatory": true,
        "studentCompleted": true,
        "studentGrade": "A"
      }
    ]
  }
]
```

---

### 9.2 Get Available Courses (Student)

```
GET /api/enrollments/available
```

**Auth Required**: βœ… Yes
**Roles**: `student` only

> Returns courses the student **can enroll in**, checking:
> - Prerequisites completed with grade **B- or higher**
> - Section has available seats
> - No schedule conflicts with current enrollments
> - Course is active and not cancelled

#### Query Parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `departmentId` | `integer` | ❌ | β€” | Filter by department |
| `semesterId` | `integer` | ❌ | β€” | Filter by semester |
| `search` | `string` | ❌ | β€” | Search in course name/code |
| `level` | `string` | ❌ | β€” | Filter by course level |
| `page` | `integer` | ❌ | `1` | Page number |
| `limit` | `integer` | ❌ | `20` | Items per page |

#### Response `200 OK`

```json
[
  {
    "id": 1,                                // number β€” Course ID
    "name": "Introduction to CS",           // string
    "code": "CS101",                         // string
    "description": "...",                    // string | null
    "credits": 3,                            // number
    "level": "FRESHMAN",                     // string β€” CourseLevel enum
    "departmentId": 3,                       // number
    "departmentName": "Computer Science",    // string
    "sections": [                            // array β€” Available sections
      {
        "id": 11,
        "sectionNumber": "1",
        "maxCapacity": 30,
        "currentEnrollment": 25,
        "availableSeats": 5,
        "location": "Room A101",
        "semesterId": 1,
        "semesterName": "Fall 2025"
      }
    ],
    "prerequisites": [                       // array β€” Required prerequisites
      {
        "id": 1,
        "courseId": 1,
        "prerequisiteCourseId": 2,
        "courseCode": "CS100",
        "courseName": "Programming Basics",
        "isMandatory": true
      }
    ],
    "canEnroll": true,                       // boolean β€” Whether student meets all requirements
    "enrollmentStatus": null                 // string | null β€” Current enrollment status if already enrolled
  }
]
```

---

### 9.3 Enroll in a Course (Student)

```
POST /api/enrollments/register
```

**Auth Required**: βœ… Yes
**Roles**: `student` only

#### Request Body

| Field | Type | Required | Description |
|---|---|---|---|
| `sectionId` | `number` | βœ… | Section ID to enroll in |

#### Example Request

```json
{
  "sectionId": 11
}
```

#### Response `201 Created`

Returns enrollment response object (same shape as items in 9.1 response).

#### Business Rules & Validation

1. **Already Enrolled**: Cannot enroll if already enrolled in the same section (throws `409`)
2. **Prerequisites**: All prerequisites must be completed with grade **B- or higher**
3. **Schedule Conflicts**: No time overlap with current enrollments in the same semester
4. **Capacity**: If section is full, student is still enrolled (waitlist not implemented)
5. **Retake Logic**:
   - If previously **failed** (grade F): Can retake freely
   - If previously **passed** with B- or better and wants to improve: Requires **admin approval** (throws `400` with `RetakeRequiresAdminApprovalException`)

#### Error Responses

| Status | Description |
|---|---|
| `400` | Prerequisites not met / Schedule conflict / User or section not found |
| `409` | Already enrolled in this section |

---

### 9.4 Drop/Withdraw from a Course

```
DELETE /api/enrollments/:id
```

**Auth Required**: βœ… Yes
**Roles**: `student` (own enrollments), `admin` (any enrollment)

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `id` | `integer` | βœ… | Enrollment ID |

#### Request Body (Optional)

| Field | Type | Required | Description |
|---|---|---|---|
| `reason` | `string` | ❌ | Drop reason from `DropReason` enum |

#### Response `200 OK`

Returns the updated enrollment object with `status: "dropped"` and `droppedAt` timestamp.

#### Business Rules

1. **Permission**: Students can only drop their own enrollments; admins can drop any
2. **Drop Deadline**: Students can only drop before **50% of semester has elapsed** (admins can override)
3. **Status Changes**: Enrollment status changes from `enrolled` β†’ `dropped`
4. **Section Count**: Section's `currentEnrollment` is decremented

#### Error Responses

| Status | Description |
|---|---|
| `400` | Drop deadline passed / Cannot drop past enrollment |
| `403` | Forbidden β€” not your enrollment |
| `404` | Enrollment not found |

---

### 9.5 Get Teaching Courses (Instructor/TA)

```
GET /api/enrollments/teaching
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`

> Returns all course sections where the user is assigned as an instructor or TA.

#### Response `200 OK`

```json
[
  {
    "sectionId": 11,
    "courseId": 1,
    "course": {
      "id": 1,
      "name": "Introduction to CS",
      "code": "CS101",
      "description": "...",
      "credits": 3,
      "level": "FRESHMAN"
    },
    "section": {
      "id": 11,
      "sectionNumber": "1",
      "maxCapacity": 30,
      "currentEnrollment": 25,
      "location": "Room A101"
    },
    "semester": {
      "id": 1,
      "name": "Fall 2025",
      "startDate": "2025-09-01",
      "endDate": "2025-12-15"
    }
  }
]
```

---

### 9.6 Get Section Students

```
GET /api/sections/:sectionId/students
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`

> Returns all **actively enrolled** students (status = `enrolled`) in a section.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `sectionId` | `integer` | βœ… | Section ID |

#### Response `200 OK`

Returns array of enrollment objects (same shape as 9.1), sorted by `enrollmentDate ASC`.

---

### 9.7 Get Section Waitlist

```
GET /api/sections/:sectionId/waitlist
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `admin`

> **Currently Not Implemented**: Returns empty array. Waitlist functionality requires a separate waitlist table.

#### Response `200 OK`

```json
[]
```

---

### 9.8 Assign Instructor to Section (Admin)

```
POST /api/enrollments/sections/:sectionId/instructors
```

**Auth Required**: βœ… Yes
**Roles**: `admin` only

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `sectionId` | `integer` | βœ… | Section ID |

#### Request Body

| Field | Type | Required | Default | Description |
|---|---|---|---|---|
| `userId` | `number` | βœ… | β€” | User ID of instructor (must have `instructor` role) |
| `role` | `string` | ❌ | `primary` | One of: `primary`, `co_instructor`, `guest` |
| `responsibilities` | `string` | ❌ | β€” | Free-text description |

#### Example Request

```json
{
  "userId": 58,
  "role": "primary",
  "responsibilities": "Lead lectures, grade assignments"
}
```

#### Response `201 Created`

```json
{
  "id": 1,                   // number β€” Instructor assignment ID
  "sectionId": 11,
  "userId": 58,
  "role": "primary",
  "responsibilities": "Lead lectures, grade assignments",
  "assignedAt": "2025-09-01T10:00:00Z",
  "user": {
    "userId": 58,
    "firstName": "Tarek",
    "lastName": "Instructor",
    "email": "tarek@example.com"
  }
}
```

#### Error Responses

| Status | Description |
|---|---|
| `400` | Invalid user ID or section ID |
| `404` | Section or user not found |
| `409` | Instructor already assigned to this section |

---

### 9.9 Get Section Instructors

```
GET /api/enrollments/sections/:sectionId/instructors
```

**Auth Required**: βœ… Yes
**Roles**: `admin`, `instructor`, `teaching_assistant`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `sectionId` | `integer` | βœ… | Section ID |

#### Response `200 OK`

Returns array of instructor assignment objects (same shape as 9.8 response).

---

### 9.10 Remove Instructor from Section (Admin)

```
DELETE /api/enrollments/sections/:sectionId/instructors/:assignmentId
```

**Auth Required**: βœ… Yes
**Roles**: `admin` only

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `sectionId` | `integer` | βœ… | Section ID |
| `assignmentId` | `integer` | βœ… | Instructor assignment ID |

#### Response `204 No Content`

Empty body.

---

### 9.11 Assign TA to Section (Admin)

```
POST /api/enrollments/sections/:sectionId/tas
```

**Auth Required**: βœ… Yes
**Roles**: `admin` only

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `sectionId` | `integer` | βœ… | Section ID |

#### Request Body

| Field | Type | Required | Description |
|---|---|---|---|
| `userId` | `number` | βœ… | User ID of TA (must have `teaching_assistant` role) |
| `responsibilities` | `string` | ❌ | Free-text description (e.g., "Grading labs, office hours Mon/Wed") |

#### Example Request

```json
{
  "userId": 60,
  "responsibilities": "Grade lab submissions, hold office hours on Tuesday"
}
```

#### Response `201 Created`

```json
{
  "id": 2,                   // number β€” TA assignment ID
  "sectionId": 11,
  "userId": 60,
  "responsibilities": "Grade lab submissions, hold office hours on Tuesday",
  "assignedAt": "2025-09-01T10:00:00Z",
  "user": {
    "userId": 60,
    "firstName": "John",
    "lastName": "TA",
    "email": "ta@example.com"
  }
}
```

#### Error Responses

| Status | Description |
|---|---|
| `400` | Invalid user ID or section ID |
| `404` | Section or user not found |
| `409` | TA already assigned to this section |

---

### 9.12 Get Section TAs

```
GET /api/enrollments/sections/:sectionId/tas
```

**Auth Required**: βœ… Yes
**Roles**: `admin`, `instructor`, `teaching_assistant`

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `sectionId` | `integer` | βœ… | Section ID |

#### Response `200 OK`

Returns array of TA assignment objects (same shape as 9.11 response).

---

### 9.13 Remove TA from Section (Admin)

```
DELETE /api/enrollments/sections/:sectionId/tas/:assignmentId
```

**Auth Required**: βœ… Yes
**Roles**: `admin` only

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `sectionId` | `integer` | βœ… | Section ID |
| `assignmentId` | `integer` | βœ… | TA assignment ID |

#### Response `204 No Content`

Empty body.

---

### 9.14 Get Section Instructor Summary

```
GET /api/enrollments/section/:sectionId/instructor
```

**Auth Required**: βœ… Yes
**Roles**: `admin`, `instructor`, `teaching_assistant`, `student`

> Returns simplified instructor info for a section.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `sectionId` | `integer` | βœ… | Section ID |

#### Response `200 OK`

```json
{
  "instructorId": 58,
  "instructor": {
    "userId": 58,
    "fullName": "Tarek Instructor",
    "email": "tarek@example.com"
  }
}
```

---

### 9.15 Get Section TA Summaries

```
GET /api/enrollments/section/:sectionId/tas
```

**Auth Required**: βœ… Yes
**Roles**: `admin`, `instructor`, `teaching_assistant`, `student`

> Returns simplified TA info for a section.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `sectionId` | `integer` | βœ… | Section ID |

#### Response `200 OK`

```json
[
  {
    "userId": 60,
    "fullName": "Tarek TA",
    "email": "ta@example.com"
  }
]
```

---

### 9.16 Get Enrollment Periods

```
GET /api/enrollments/periods
```

**Auth Required**: βœ… Yes
**Roles**: All authenticated users

> Returns semesters with registration date ranges.

#### Response `200 OK`

```json
[
  {
    "id": 1,
    "semesterName": "Fall 2025",
    "semesterCode": "FA25",
    "registrationStart": "2025-08-01T00:00:00Z",
    "registrationEnd": "2025-08-25T23:59:59Z",
    "semesterStart": "2025-09-01T00:00:00Z",
    "semesterEnd": "2025-12-15T23:59:59Z",
    "status": "active"
  }
]
```

---

## 10. Error Handling

### 9.1 Standard Error Response Shape

```json
{
  "statusCode": 404,
  "message": "Assignment not found",
  "error": "Not Found"
}
```

Or for validation errors (`400`):

```json
{
  "statusCode": 400,
  "message": [
    "courseId must be a number",
    "title must be longer than or equal to 3 characters"
  ],
  "error": "Bad Request"
}
```

### 9.2 Common Error Codes

| Status | When |
|---|---|
| `400` | Validation failure, invalid state transition, business rule violation |
| `401` | Missing or invalid JWT token |
| `403` | Insufficient role permissions |
| `404` | Resource not found |
| `409` | Duplicate resource (e.g., course code) |

### 9.3 Business Rule Errors (400)

| Module | Error | Description |
|---|---|---|
| Courses | Course code exists | `CourseCodeAlreadyExistsException` β€” code+department must be unique |
| Courses | Circular prerequisite | `CircularPrerequisiteDetectedException` β€” detected via DFS |
| Courses | Delete with sections | `CannotDeleteCourseWithActiveSectionsException` |
| Assignments | Not published | `AssignmentNotPublishedException` β€” must be `published` to submit |
| Assignments | Not available yet | `AssignmentNotAvailableYetException` β€” before `availableFrom` |
| Assignments | Deadline passed | `SubmissionDeadlinePassedException` β€” past `dueDate` and late not allowed |
| Assignments | Not enrolled | Student not enrolled in the course |
| Assignments | Invalid transition | Status transition not allowed (e.g., `draft` to `closed`) |
| Sections | Section full | `SectionFullException` β€” enrollment exceeds capacity |
| Sections | Capacity reduction | Cannot reduce capacity below current enrollment |
| Schedules | Invalid time | `InvalidTimeRangeException` β€” end time <= start time |
| Schedules | Conflict | `ScheduleConflictException` β€” room/time overlap |

---

## 10. Flutter Integration Tips

### 10.1 HTTP Client Setup

```dart
// Base configuration
const baseUrl = 'http://your-server:3001';

// Auth header
final headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer $accessToken',
};
```

### 10.2 Parsing `lateSubmissionAllowed`

The backend stores this as a MySQL `TINYINT(1)` β€” it comes back as `0` or `1` (number), not `true`/`false`:

```dart
final isLateAllowed = (assignment['lateSubmissionAllowed'] as num) == 1;
```

### 10.3 Parsing `allowedFileTypes`

This field is a **JSON string** (not an array). Parse it:

```dart
final List<String> fileTypes = assignment['allowedFileTypes'] != null
    ? List<String>.from(jsonDecode(assignment['allowedFileTypes']))
    : [];
```

### 10.4 Decimal Fields

`maxScore`, `weight`, `latePenaltyPercent`, `score` come back as decimal numbers (may be strings from some DB drivers). Always parse:

```dart
final maxScore = double.tryParse(assignment['maxScore'].toString()) ?? 100.0;
```

### 10.5 File Uploads (multipart/form-data)

Use `dio` or `http.MultipartRequest`:

```dart
// Using Dio
final formData = FormData.fromMap({
  'file': await MultipartFile.fromFile(filePath, filename: fileName),
  'title': 'My submission',
  'submissionText': 'Notes here',
});

final response = await dio.post(
  '$baseUrl/api/assignments/3/submissions/upload',
  data: formData,
  options: Options(headers: {'Authorization': 'Bearer $token'}),
);
```

### 10.6 Pagination Helper

```dart
class PaginatedResponse<T> {
  final List<T> data;
  final int total;
  final int page;
  final int limit;
  final int totalPages;

  bool get hasNextPage => page < totalPages;
  bool get hasPreviousPage => page > 1;
}
```

### 10.7 Enum Mapping

```dart
enum AssignmentStatus { draft, published, closed, archived }

extension AssignmentStatusExt on AssignmentStatus {
  String get value => name; // 'draft', 'published', etc.

  static AssignmentStatus fromString(String s) =>
    AssignmentStatus.values.firstWhere((e) => e.name == s);
}
```

### 10.8 Date Handling

All dates are ISO 8601 strings. Parse with:

```dart
final dueDate = DateTime.parse(assignment['dueDate']); // UTC
final localDueDate = dueDate.toLocal(); // Convert to local timezone
```

### 10.9 Role-Based UI

```dart
// Show/hide actions based on role
final userRoles = currentUser.roles; // List<String>
final canCreateAssignment = userRoles.any(
  (r) => ['instructor', 'admin'].contains(r),
);
final canSubmit = userRoles.contains('student');
final canGrade = userRoles.any(
  (r) => ['instructor', 'teaching_assistant'].contains(r),
);
```

### 10.10 Handling `isLate` Differences

| Module | `isLate` Type | Values |
|---|---|---|
| Assignments | `number` (tinyint) | `0` = on-time, `1` = late |
| Labs | `boolean` | `true` / `false` |

```dart
// Assignments
final isLate = (submission['isLate'] as num) == 1;

// Labs
final isLate = submission['isLate'] as bool;
```

---

## 11. Course Materials & Video Lectures Module

**Base Path**: `/api/courses/:courseId/materials`

> **All endpoints require JWT authentication** (`@UseGuards(JwtAuthGuard, RolesGuard)`).
> This module handles uploading, viewing, organizing, and managing all course materials β€” including **video lectures** uploaded to YouTube and **documents** stored on Google Drive.

### 11.0 Enums Reference (Course Materials)

#### MaterialType
| Value | Description |
|---|---|
| `lecture` | Lecture content (notes, handouts) |
| `slide` | Presentation slides |
| `video` | Video content (YouTube integration) |
| `reading` | Reading material |
| `link` | External link |
| `document` | Generic document |
| `other` | Uncategorized material |

#### OrganizationType (for Course Structure)
| Value | Description |
|---|---|
| `lecture` | Main lecture content |
| `section` | Discussion or tutorial section |
| `lab` | Hands-on lab session |
| `tutorial` | Tutorial session |

### 11.0.1 Database Entities

#### `course_materials` Table

| Column | DB Type | TS Type | Nullable | Default | Description |
|---|---|---|---|---|---|
| `material_id` | `bigint unsigned` | `number` | ❌ (PK) | Auto | Primary key |
| `course_id` | `bigint unsigned` | `number` | ❌ | β€” | FK β†’ `courses` |
| `file_id` | `bigint unsigned` | `number \| null` | βœ… | `null` | FK β†’ `files` (local files) |
| `drive_file_id` | `bigint unsigned` | `number \| null` | βœ… | `null` | FK β†’ `drive_files` (Google Drive) |
| `material_type` | `enum('lecture','slide','video','reading','link','document','other')` | `MaterialType` | ❌ | `'document'` | Type of material |
| `title` | `varchar(255)` | `string` | ❌ | β€” | Material title |
| `description` | `text` | `string \| null` | βœ… | `null` | Description |
| `external_url` | `varchar(500)` | `string \| null` | βœ… | `null` | External URL (YouTube embed URL, Google Drive link, etc.) |
| `youtube_video_id` | `varchar(50)` | `string \| null` | βœ… | `null` | YouTube video ID (for video materials) |
| `order_index` | `int` | `number` | ❌ | `0` | Sort order within week |
| `week_number` | `int` | `number \| null` | βœ… | `null` | Week number for organizing by course week |
| `view_count` | `int` | `number` | ❌ | `0` | Number of times viewed |
| `download_count` | `int` | `number` | ❌ | `0` | Number of times downloaded |
| `uploaded_by` | `bigint unsigned` | `number` | ❌ | β€” | FK β†’ `users` (creator) |
| `is_published` | `tinyint` | `boolean` | ❌ | `0` | `0` = draft (hidden), `1` = published (visible to students) |
| `published_at` | `timestamp` | `Date \| null` | βœ… | `null` | When material was first published |
| `created_at` | `timestamp` | `Date` | ❌ | Auto | Creation timestamp |
| `updated_at` | `timestamp` | `Date` | ❌ | Auto | Last update timestamp |

**Indexes**: `course_id`, `uploaded_by`, `material_type`, `week_number`

#### `lecture_sections_labs` Table (Course Structure)

| Column | DB Type | TS Type | Nullable | Default | Description |
|---|---|---|---|---|---|
| `organization_id` | `bigint unsigned` | `number` | ❌ (PK) | Auto | Primary key |
| `course_id` | `bigint unsigned` | `number` | ❌ | β€” | FK β†’ `courses` |
| `material_id` | `bigint unsigned` | `number \| null` | βœ… | `null` | FK β†’ `course_materials` |
| `organization_type` | `enum('lecture','section','lab','tutorial')` | `OrganizationType \| null` | βœ… | `null` | Type of content organization |
| `title` | `varchar(255)` | `string` | ❌ | β€” | Structure item title |
| `week_number` | `int` | `number \| null` | βœ… | `null` | Week number |
| `order_index` | `int` | `number` | ❌ | `0` | Sort order |
| `description` | `text` | `string \| null` | βœ… | `null` | Description |
| `created_at` | `timestamp` | `Date` | ❌ | Auto | Creation timestamp |
| `updated_at` | `timestamp` | `Date` | ❌ | Auto | Last update timestamp |

**Indexes**: `course_id`, `week_number`

---

### 11.1 List Course Materials

```
GET /api/courses/:courseId/materials
```

**Auth Required**: βœ… Yes
**Roles**: All authenticated users (role-based visibility filtering)

#### Role-Based Visibility

| Role | Can See |
|---|---|
| `student` | Only **published** materials (`is_published = 1`) |
| `instructor` | All materials (including drafts) |
| `teaching_assistant` | All materials (including drafts) |
| `admin` / `it_admin` | All materials (including drafts) |

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |

#### Query Parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `materialType` | `string` | ❌ | β€” | Filter by `MaterialType` enum (`lecture`, `slide`, `video`, `reading`, `link`, `document`, `other`) |
| `weekNumber` | `integer` | ❌ | β€” | Filter by week number |
| `isPublished` | `boolean` | ❌ | β€” | Filter by visibility. Only effective for `instructor`, `ta`, `admin` roles. Ignored for students. |
| `search` | `string` | ❌ | β€” | Search in title and description (partial match / `LIKE`) |
| `sortBy` | `string` | ❌ | `orderIndex` | Sort field: `createdAt`, `title`, `orderIndex` |
| `sortOrder` | `string` | ❌ | `ASC` | Sort order: `ASC` or `DESC` |
| `page` | `integer` | ❌ | `1` | Page number (1-indexed, min: 1) |
| `limit` | `integer` | ❌ | `10` | Items per page (1-100) |

#### Response `200 OK`

```json
{
  "data": [
    {
      "materialId": 1,                              // number (bigint) β€” Material ID (PK)
      "courseId": 1,                                 // number β€” FK to courses
      "fileId": null,                               // number | null β€” FK to local files
      "driveFileId": 123,                           // number | null β€” FK to drive_files
      "materialType": "video",                      // string β€” MaterialType enum
      "title": "Lecture 1: Introduction to DS",     // string β€” Material title (max 255)
      "description": "Covers basics of...",         // string | null β€” Description
      "externalUrl": "https://www.youtube.com/embed/abc123",  // string | null β€” YouTube embed URL or Drive view URL
      "youtubeVideoId": "abc123",                   // string | null β€” YouTube video ID
      "orderIndex": 0,                              // number β€” Sort position
      "weekNumber": 1,                              // number | null β€” Week number
      "viewCount": 42,                              // number β€” Times viewed
      "downloadCount": 10,                          // number β€” Times downloaded
      "uploadedBy": 5,                              // number β€” Creator user ID
      "isPublished": true,                          // boolean β€” Visibility state (tinyint 0/1 mapped to boolean)
      "publishedAt": "2025-06-01T10:00:00Z",        // string | null β€” ISO 8601 timestamp
      "createdAt": "2025-06-01T08:00:00Z",           // string β€” ISO 8601
      "updatedAt": "2025-06-01T08:00:00Z",           // string β€” ISO 8601
      "course": {                                    // object β€” Joined course relation
        "id": 1,
        "departmentId": 3,
        "name": "Introduction to CS",
        "code": "CS101"
      },
      "file": null,                                  // object | null β€” Joined local file relation
      "uploader": {                                  // object β€” Joined uploader user relation
        "user_id": 5,
        "first_name": "Dr. Jane",
        "last_name": "Smith",
        "email": "jane@example.com"
      }
    }
  ],
  "meta": {
    "total": 25,         // number β€” Total matching records
    "page": 1,           // number β€” Current page
    "limit": 10,         // number β€” Items per page
    "totalPages": 3      // number β€” Total pages
  }
}
```

---

### 11.2 Get Material by ID

```
GET /api/courses/:courseId/materials/:id
```

**Auth Required**: βœ… Yes
**Roles**: All authenticated users

> **Students** can only view materials where `isPublished = true`. Requesting an unpublished material as a student returns `404 Not Found`.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |
| `id` | `integer` | βœ… | Material ID |

#### Response `200 OK`

Returns a single material object (same shape as items in 11.1 `data` array, including `course`, `file`, and `uploader` relations).

#### Error Responses

| Status | Description |
|---|---|
| `401` | Unauthorized β€” missing or invalid token |
| `404` | Material not found (or unpublished material accessed by student) |

---

### 11.3 Create Course Material

```
POST /api/courses/:courseId/materials
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`, `it_admin`

> **Authorization**: Non-admin users must be **assigned to the course** (as instructor of a section or TA of a section). Unassigned instructors/TAs receive `403 Forbidden`.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |

#### Request Body (`application/json`)

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `title` | `string` | βœ… | Max 255 chars, non-empty | Material title |
| `materialType` | `string` | βœ… | `MaterialType` enum | Type of material |
| `description` | `string` | ❌ | β€” | Material description |
| `fileId` | `number` | ❌ | Must reference valid file ID | File ID from the Files module |
| `externalUrl` | `string` | ❌ | Max 500 chars | External URL (YouTube link, external resource, etc.) |
| `orderIndex` | `number` | ❌ | Min 0 | Sort order for display |
| `weekNumber` | `number` | ❌ | Min 1 | Week number for content organization |
| `isPublished` | `boolean` | ❌ | β€” | Publish immediately (`true`) or save as draft (`false`). **Default: `false`** |

#### Example Request

```json
{
  "title": "Lecture 1: Introduction to Programming",
  "materialType": "video",
  "description": "Introduction to basic programming concepts.",
  "externalUrl": "https://www.youtube.com/watch?v=example",
  "weekNumber": 1,
  "orderIndex": 0,
  "isPublished": false
}
```

#### Response `201 Created`

Returns the created material object (same shape as items in 11.1 response without `course`/`file`/`uploader` relations β€” raw entity).

#### Error Responses

| Status | Description |
|---|---|
| `400` | Invalid input data (validation failure) |
| `403` | Forbidden β€” user not assigned to this course |

---

### 11.4 Bulk Create Materials

```
POST /api/courses/:courseId/materials/bulk
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`, `it_admin`

> Maximum **50 materials** per request. Non-admin users must be assigned to the course.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |

#### Request Body (`application/json`)

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `materials` | `CreateMaterialDto[]` | βœ… | 1-50 items, validated individually | Array of material objects (same shape as 11.3 request body) |

#### Example Request

```json
{
  "materials": [
    {
      "title": "Lecture 1: Introduction",
      "materialType": "lecture",
      "description": "Introduction to the course",
      "weekNumber": 1
    },
    {
      "title": "Lecture 2: Fundamentals",
      "materialType": "lecture",
      "description": "Fundamentals of the subject",
      "weekNumber": 1
    }
  ]
}
```

#### Response `201 Created`

```json
{
  "message": "Successfully created 2 materials",  // string β€” Success message
  "count": 2,                                      // number β€” Count of created items
  "data": [                                        // CourseMaterial[] β€” Created material objects
    {
      "materialId": 10,
      "courseId": 1,
      "title": "Lecture 1: Introduction",
      "materialType": "lecture",
      "description": "Introduction to the course",
      "weekNumber": 1,
      "orderIndex": 0,
      "isPublished": false,
      "uploadedBy": 5,
      "createdAt": "2025-06-01T08:00:00Z",
      "updatedAt": "2025-06-01T08:00:00Z"
    }
  ]
}
```

#### Error Responses

| Status | Description |
|---|---|
| `400` | Invalid input data β€” minimum 1 material required, maximum 50 allowed |
| `403` | Forbidden β€” user not assigned to this course |

---

### 11.5 Upload Video Material (YouTube)

```
POST /api/courses/:courseId/materials/video
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`, `it_admin`
**Content-Type**: `multipart/form-data`

> **This is the primary endpoint for uploading video lectures.**
> The backend uploads the video to YouTube as **unlisted**, then creates a `course_materials` record with the YouTube embed URL and video ID.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |

#### Form Data Fields

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `video` | `binary (file)` | βœ… | Formats: `mp4`, `avi`, `mov`, `webm`, `mkv`, `flv`, `wmv` | Video file to upload |
| `title` | `string` | βœ… | Max 255 chars, non-empty | Video title |
| `description` | `string` | ❌ | β€” | Video description |
| `tags` | `string[]` | ❌ | Array of strings | Tags for the YouTube video |
| `weekNumber` | `integer` | ❌ | 1–52 | Week to assign the video to |
| `orderIndex` | `integer` | ❌ | Min 0, default: `0` | Sort order within the week |
| `isPublished` | `boolean` | ❌ | Default: `false` | Publish immediately or save as draft |

#### Upload Flow (Internal)

1. Backend validates user is authorized for this course
2. Video file buffer is uploaded to **YouTube** (privacy: `unlisted`)
3. YouTube returns `videoId` and URL
4. A `course_materials` record is created with:
   - `materialType` = `video`
   - `externalUrl` = `https://www.youtube.com/embed/{videoId}`
   - `youtubeVideoId` = the YouTube video ID
   - Other metadata (`weekNumber`, `orderIndex`, `isPublished`)

#### Response `201 Created`

```json
{
  "materialId": 1,                                           // number β€” Created material ID
  "courseId": 1,                                             // number β€” Course ID
  "title": "Lecture 1: Introduction",                        // string β€” Video title
  "materialType": "video",                                   // string β€” Always "video"
  "description": "This covers the basics...",                // string | null
  "externalUrl": "https://www.youtube.com/embed/dQw4w9WgXcQ", // string β€” YouTube embed URL
  "youtubeVideoId": "dQw4w9WgXcQ",                          // string β€” YouTube video ID
  "weekNumber": 1,                                           // number | null
  "orderIndex": 0,                                           // number
  "isPublished": false,                                      // boolean
  "publishedAt": null,                                       // string | null
  "uploadedBy": 5,                                           // number
  "viewCount": 0,                                            // number
  "downloadCount": 0,                                        // number
  "createdAt": "2025-06-01T08:00:00Z",                       // string β€” ISO 8601
  "updatedAt": "2025-06-01T08:00:00Z",                       // string β€” ISO 8601
  "youtubeUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ", // string β€” Full YouTube watch URL (appended by service)
  "embedUrl": "https://www.youtube.com/embed/dQw4w9WgXcQ"    // string β€” Embed URL for iframe (appended by service)
}
```

#### Error Responses

| Status | Description |
|---|---|
| `400` | No video file provided / YouTube upload failed / Invalid input data |
| `403` | Forbidden β€” user not assigned to this course |
| `413` | Video file too large (YouTube account limits apply) |

---

### 11.6 Upload Document Material (Google Drive)

```
POST /api/courses/:courseId/materials/document
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`, `it_admin`
**Content-Type**: `multipart/form-data`

> Uploads a document to **Google Drive** in the appropriate course folder hierarchy and creates a material record.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |

#### Form Data Fields

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `document` | `binary (file)` | βœ… | Formats: `pdf`, `ppt`, `pptx`, `doc`, `docx`, `xls`, `xlsx`, `txt`, `md`, `zip` | Document file to upload |
| `title` | `string` | βœ… | Max 255 chars, non-empty | Document title |
| `description` | `string` | ❌ | β€” | Document description |
| `materialType` | `string` | ❌ | `MaterialType` enum, default: `document` | Document type: `lecture`, `slide`, `reading`, `document`, `link` |
| `weekNumber` | `integer` | ❌ | 1–52 | Week to assign the document to |
| `orderIndex` | `integer` | ❌ | Min 0, default: `0` | Sort order within the week |
| `isPublished` | `boolean` | ❌ | Default: `false` | Publish immediately or save as draft |

#### Folder Placement Rules

| `materialType` value | Google Drive folder target |
|---|---|
| `lecture` | `Course/Lectures/` |
| `slide` | `Course/Lectures/` (slides grouped with lectures) |
| `reading` | `Course/General/` |
| `document` | `Course/General/` |
| `link` | `Course/General/` |
| _other_ | `Course/General/` |

#### File Naming Convention

Files are renamed following the pattern:
```
{WeekNN_}{SafeTitle}_v1.{ext}
```
- Example: `Week01_Introduction_to_Data_Structures_v1.pdf`

#### Response `201 Created`

```json
{
  "materialId": 2,                                                          // number β€” Created material ID
  "courseId": 1,                                                            // number
  "title": "Week 1 Lecture Notes",                                          // string
  "materialType": "lecture",                                                // string β€” MaterialType enum
  "description": "Comprehensive lecture notes covering the basics.",         // string | null
  "externalUrl": "https://drive.google.com/file/d/abc123/view",             // string β€” Google Drive view URL
  "driveFileId": 123,                                                       // number β€” FK to drive_files table
  "weekNumber": 1,                                                          // number | null
  "orderIndex": 0,                                                          // number
  "isPublished": false,                                                     // boolean
  "publishedAt": null,                                                      // string | null
  "uploadedBy": 5,                                                          // number
  "createdAt": "2025-06-01T08:00:00Z",                                      // string β€” ISO 8601
  "updatedAt": "2025-06-01T08:00:00Z",                                      // string β€” ISO 8601
  "driveId": "abc123",                                                      // string β€” Google Drive file ID (appended)
  "driveViewUrl": "https://drive.google.com/file/d/abc123/view",            // string β€” View URL (appended)
  "driveDownloadUrl": "https://drive.google.com/uc?id=abc123&export=download", // string β€” Download URL (appended)
  "fileName": "Week01_Week_1_Lecture_Notes_v1.pdf"                          // string β€” Generated file name (appended)
}
```

#### Error Responses

| Status | Description |
|---|---|
| `400` | No document file / Google Drive upload failed / Invalid input data |
| `403` | Forbidden β€” user not assigned to this course |

---

### 11.7 Update Material

```
PUT /api/courses/:courseId/materials/:id
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`, `it_admin`

> **Ownership**: Non-admin users can only update materials **they uploaded** (`uploadedBy` must match the requesting user). Admins can update any material.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |
| `id` | `integer` | βœ… | Material ID |

#### Request Body (`application/json`) β€” All fields optional (uses `PartialType` of `CreateMaterialDto`)

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `title` | `string` | ❌ | Max 255 chars | Updated title |
| `materialType` | `string` | ❌ | `MaterialType` enum | Updated type |
| `description` | `string` | ❌ | β€” | Updated description |
| `fileId` | `number` | ❌ | Must exist | Updated file reference |
| `externalUrl` | `string` | ❌ | Max 500 chars | Updated external URL |
| `orderIndex` | `number` | ❌ | Min 0 | Updated sort order |
| `weekNumber` | `number` | ❌ | Min 1 | Updated week number |
| `isPublished` | `boolean` | ❌ | β€” | Updated visibility. If changing from `false` β†’ `true`, `publishedAt` is set automatically. |

#### Response `200 OK`

Returns the updated material object (with `course`, `file`, `uploader` relations).

#### Error Responses

| Status | Description |
|---|---|
| `403` | Forbidden β€” you can only update materials you uploaded (non-admin) |
| `404` | Material not found |

---

### 11.8 Delete Material

```
DELETE /api/courses/:courseId/materials/:id
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`, `it_admin`

> **Ownership**: Non-admin users can only delete materials **they uploaded**. Admins can delete any material.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |
| `id` | `integer` | βœ… | Material ID |

#### Response `200 OK`

```json
{
  "message": "Material deleted successfully"   // string
}
```

#### Error Responses

| Status | Description |
|---|---|
| `403` | Forbidden β€” you can only delete materials you uploaded (non-admin) |
| `404` | Material not found |

---

### 11.9 Toggle Material Visibility

```
PATCH /api/courses/:courseId/materials/:id/visibility
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `teaching_assistant`, `admin`, `it_admin`

> Controls whether a material is visible to students. Non-admin users can only toggle visibility of materials **they uploaded**.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |
| `id` | `integer` | βœ… | Material ID |

#### Request Body (`application/json`)

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `isPublished` | `boolean` | βœ… | β€” | `true` = visible to students, `false` = draft (hidden) |

#### Example Request

```json
{
  "isPublished": true
}
```

#### Response `200 OK`

Returns the updated material object (full entity with `course`, `file`, `uploader` relations). `publishedAt` is set to current timestamp on first publish, preserved on subsequent toggles.

#### Error Responses

| Status | Description |
|---|---|
| `403` | Forbidden β€” you can only change visibility of materials you uploaded (non-admin) |
| `404` | Material not found |

---

### 11.10 Download Material

```
GET /api/courses/:courseId/materials/:id/download
```

**Auth Required**: βœ… Yes
**Roles**: All authenticated users

> Students can only download **published** materials. Increments `downloadCount` on each successful call.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |
| `id` | `integer` | βœ… | Material ID |

#### Response `200 OK`

```json
{
  "material": {                          // object β€” Full material entity
    "materialId": 1,
    "title": "Lecture Notes Week 1",
    "materialType": "lecture",
    "fileId": 12,
    "externalUrl": null,
    "viewCount": 42,
    "downloadCount": 11
    // ... full material object fields
  },
  "file": {                              // object β€” Associated file entity
    "fileId": 12,
    "fileName": "lecture_notes_w1.pdf",
    "filePath": "/uploads/materials/lecture_notes_w1.pdf",
    "fileSize": 2048576,
    "mimeType": "application/pdf"
    // ... full file object fields
  },
  "downloadUrl": "/uploads/materials/lecture_notes_w1.pdf"   // string β€” Direct download path
}
```

#### Error Responses

| Status | Description |
|---|---|
| `400` | Material does not have a downloadable file (`fileId` is null) |
| `404` | Material or associated file not found |

---

### 11.11 Track Material View

```
POST /api/courses/:courseId/materials/:id/view
```

**Auth Required**: βœ… Yes
**Roles**: All authenticated users

> Records that a user viewed a material. Increments `viewCount` counter. Used for analytics and engagement tracking.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |
| `id` | `integer` | βœ… | Material ID |

#### Request Body

_None_ (empty body)

#### Response `200 OK`

```json
{
  "message": "View tracked successfully",   // string
  "materialId": 1,                          // number β€” Material ID
  "viewCount": 43                           // number β€” New total view count
}
```

#### Error Responses

| Status | Description |
|---|---|
| `404` | Material not found |

---

### 11.12 Get Embed URL (Video Materials)

```
GET /api/courses/:courseId/materials/:id/embed
```

**Auth Required**: βœ… Yes
**Roles**: All authenticated users

> For **video** materials only. Returns the YouTube embed URL and ready-to-use iframe HTML.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |
| `id` | `integer` | βœ… | Material ID |

#### Response `200 OK` (YouTube video)

```json
{
  "videoId": "dQw4w9WgXcQ",                                    // string β€” YouTube video ID
  "embedUrl": "https://www.youtube.com/embed/dQw4w9WgXcQ",     // string β€” Embed URL for iframe
  "iframeHtml": "<iframe width=\"560\" height=\"315\" src=\"https://www.youtube.com/embed/dQw4w9WgXcQ\" frameborder=\"0\" allowfullscreen></iframe>"  // string β€” Ready-to-use iframe HTML
}
```

#### Response `200 OK` (Non-YouTube external URL)

```json
{
  "externalUrl": "https://example.com/video.mp4"   // string β€” Raw external URL
}
```

#### Error Responses

| Status | Description |
|---|---|
| `400` | Material is not a video (`materialType !== 'video'`) or has no external URL |
| `404` | Material not found |

---

## 12. Course Structure Module

**Base Path**: `/api/courses/:courseId/structure`

> **All endpoints require JWT authentication** (`@UseGuards(JwtAuthGuard, RolesGuard)`).
> This module provides the organizational layer for course content β€” mapping materials into weeks, lectures, sections, and labs.

---

### 12.1 Get Course Structure

```
GET /api/courses/:courseId/structure
```

**Auth Required**: βœ… Yes
**Roles**: All authenticated users

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |

#### Response `200 OK`

```json
{
  "data": [                                   // LectureSectionLab[] β€” Flat list of all structure items
    {
      "organizationId": 1,                   // number β€” Structure item ID (PK)
      "courseId": 1,                          // number β€” FK to courses
      "materialId": 5,                        // number | null β€” FK to course_materials
      "organizationType": "lecture",          // string | null β€” OrganizationType enum
      "title": "Week 1: Introduction",        // string β€” Item title
      "weekNumber": 1,                        // number | null β€” Week number
      "orderIndex": 0,                        // number β€” Sort position
      "description": "Overview of course",    // string | null
      "createdAt": "2025-06-01T08:00:00Z",    // string β€” ISO 8601
      "updatedAt": "2025-06-01T08:00:00Z",    // string β€” ISO 8601
      "material": {                           // object | null β€” Joined material relation
        "materialId": 5,
        "title": "Lecture 1 Slides",
        "materialType": "slide",
        "externalUrl": "https://drive.google.com/...",
        "youtubeVideoId": null,
        "weekNumber": 1,
        "viewCount": 20,
        "isPublished": true
      }
    }
  ],
  "byWeek": {                                // Record<number, LectureSectionLab[]> β€” Grouped by week
    "0": [ /* items without a week */ ],
    "1": [ /* week 1 items */ ],
    "2": [ /* week 2 items */ ]
  }
}
```

> **Sorting**: Items sorted by `weekNumber ASC`, then `orderIndex ASC`.

---

### 12.2 Get Structure Item by ID

```
GET /api/courses/:courseId/structure/:id
```

**Auth Required**: βœ… Yes
**Roles**: All authenticated users

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |
| `id` | `integer` | βœ… | Structure item ID |

#### Response `200 OK`

Returns a single structure item with `course` and `material` relations joined.

```json
{
  "organizationId": 1,
  "courseId": 1,
  "materialId": 5,
  "organizationType": "lecture",
  "title": "Week 1: Introduction",
  "weekNumber": 1,
  "orderIndex": 0,
  "description": "Overview of the course",
  "createdAt": "2025-06-01T08:00:00Z",
  "updatedAt": "2025-06-01T08:00:00Z",
  "course": {
    "id": 1,
    "name": "Introduction to CS",
    "code": "CS101"
  },
  "material": {
    "materialId": 5,
    "title": "Lecture 1 Slides",
    "materialType": "slide"
  }
}
```

#### Error Responses

| Status | Description |
|---|---|
| `404` | Structure item not found |

---

### 12.3 Create Structure Item

```
POST /api/courses/:courseId/structure
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `admin`, `it_admin`

> **Note**: TAs **cannot** create structure items. Non-admin instructors must be assigned to the course.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |

#### Request Body (`application/json`)

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `title` | `string` | βœ… | Max 255 chars, non-empty | Structure item title |
| `organizationType` | `string` | βœ… | `OrganizationType` enum (`lecture`, `section`, `lab`, `tutorial`) | Type of content |
| `description` | `string` | ❌ | β€” | Description of this content section |
| `weekNumber` | `number` | ❌ | Min 1 | Week number for this content |
| `orderIndex` | `number` | ❌ | Min 0. **Auto-calculated** if omitted (max existing + 1 within the week). | Sort order |
| `materialId` | `number` | ❌ | Must reference valid material ID | Link to an existing material |

#### Example Request

```json
{
  "title": "Week 1: Introduction to Data Structures",
  "organizationType": "lecture",
  "description": "Introduction to the course and basic concepts",
  "weekNumber": 1,
  "materialId": 5
}
```

#### Response `201 Created`

Returns the created structure item entity.

#### Error Responses

| Status | Description |
|---|---|
| `400` | Invalid input data |
| `403` | Forbidden β€” only instructors/admins; must be assigned to course |

---

### 12.4 Update Structure Item

```
PUT /api/courses/:courseId/structure/:id
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `admin`, `it_admin`

> All fields from `CreateStructureDto` are optional (`PartialType`). TAs cannot update structure. Non-admin instructors must be assigned to the course.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |
| `id` | `integer` | βœ… | Structure item ID |

#### Request Body (`application/json`) β€” All fields optional

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `title` | `string` | ❌ | Max 255 chars | Updated title |
| `organizationType` | `string` | ❌ | `OrganizationType` enum | Updated type |
| `description` | `string` | ❌ | β€” | Updated description |
| `weekNumber` | `number` | ❌ | Min 1 | Updated week number |
| `orderIndex` | `number` | ❌ | Min 0 | Updated sort order |
| `materialId` | `number` | ❌ | Valid material ID | Updated material link |

#### Response `200 OK`

Returns the updated structure item entity.

#### Error Responses

| Status | Description |
|---|---|
| `403` | Forbidden β€” only instructors/admins; must be assigned |
| `404` | Structure item not found |

---

### 12.5 Delete Structure Item

```
DELETE /api/courses/:courseId/structure/:id
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `admin`, `it_admin`

> **Important**: Deleting a structure item does **NOT** delete associated materials. The material remains in the `course_materials` table.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |
| `id` | `integer` | βœ… | Structure item ID |

#### Response `200 OK`

```json
{
  "message": "Structure item deleted successfully"   // string
}
```

#### Error Responses

| Status | Description |
|---|---|
| `403` | Forbidden β€” only instructors/admins; must be assigned |
| `404` | Structure item not found |

---

### 12.6 Reorder Structure Items

```
PATCH /api/courses/:courseId/structure/reorder
```

**Auth Required**: βœ… Yes
**Roles**: `instructor`, `admin`, `it_admin`

> Reorders multiple structure items in a single request. All IDs must belong to the specified course.

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `courseId` | `integer` | βœ… | Course ID |

#### Request Body (`application/json`)

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `orderIds` | `number[]` | βœ… | Non-empty array of existing structure item IDs | Array of item IDs in the desired new order |

#### Example Request

```json
{
  "orderIds": [3, 1, 2, 4]
}
```

> This would set:
> - ID 3 β†’ `orderIndex: 0`
> - ID 1 β†’ `orderIndex: 1`
> - ID 2 β†’ `orderIndex: 2`
> - ID 4 β†’ `orderIndex: 3`

#### Response `200 OK`

```json
{
  "message": "Structure reordered successfully"   // string
}
```

#### Error Responses

| Status | Description |
|---|---|
| `400` | Invalid input data (empty array, non-number values) |
| `403` | Forbidden β€” only instructors/admins; must be assigned |
| `404` | Some structure items not found or do not belong to this course |

---

## 13. YouTube Integration Module

**Base Path**: `/youtube`

> This module provides **standalone YouTube API integration** for OAuth authentication, video upload, search, and video details retrieval.
> ⚠️ These endpoints are primarily used internally by the Course Materials module (section 11.5) but are also exposed directly for advanced use cases.

---

### 13.1 Get YouTube Auth URL

```
GET /youtube/auth
```

**Auth Required**: ❌ No (Public endpoint)
**Roles**: None

> Returns the Google OAuth2 authorization URL. The user must visit this URL to grant YouTube upload permission.

#### Response `200 OK`

```json
{
  "authUrl": "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.upload&response_type=code&client_id=xxx&redirect_uri=xxx&prompt=consent"
  // string β€” Full OAuth2 URL to redirect the user to
}
```

---

### 13.2 Handle YouTube OAuth Callback

```
GET /youtube/callback
```

**Auth Required**: ❌ No (Called by Google redirect)
**Roles**: None

> Exchanges the authorization code (received from Google after user consent) for access/refresh tokens.

#### Query Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `code` | `string` | βœ… | Authorization code from Google OAuth redirect |

#### Response `200 OK`

```json
{
  "message": "Authentication successful",          // string
  "refreshToken": "ya29.a0AfB_byC..."              // string β€” Refresh token for future API calls
}
```

#### Error Responses

| Status | Description |
|---|---|
| `400` | Invalid or expired authorization code |

---

### 13.3 Upload Video to YouTube (Standalone)

```
POST /youtube/upload
```

**Auth Required**: βœ… Requires YouTube OAuth configured (refresh token in environment)
**Roles**: Any user with YouTube credentials
**Content-Type**: `multipart/form-data`

> **Note**: For uploading course lecture videos, prefer the dedicated endpoint `POST /api/courses/:courseId/materials/video` (section 11.5) which also creates the material record.

#### Form Data Fields

| Field | Type | Required | Constraints | Description |
|---|---|---|---|---|
| `video` | `binary (file)` | βœ… | MP4, AVI, MOV, WMV, FLV, WebM | Video file |
| `title` | `string` | βœ… | β€” | Video title |
| `description` | `string` | βœ… | β€” | Video description |
| `tags` | `string` | ❌ | Comma-separated string | Tags (e.g. `"education,course,lecture"`) |

> **Note**: `tags` here is a **comma-separated string**, not an array (unlike the Course Materials video endpoint).

#### Response `201 Created`

```json
{
  "success": true,                                              // boolean
  "videoId": "dQw4w9WgXcQ",                                    // string β€” YouTube video ID
  "videoUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",   // string β€” Full watch URL
  "data": {                                                     // object β€” Full YouTube API response data
    "kind": "youtube#video",
    "etag": "...",
    "id": "dQw4w9WgXcQ",
    "snippet": {
      "title": "My Course Lecture",
      "description": "Lecture about...",
      "tags": ["education", "course", "lecture"],
      "categoryId": "22"
    },
    "status": {
      "privacyStatus": "unlisted"
    }
  }
}
```

#### Error Responses

| Status | Description |
|---|---|
| `400` | No video file or invalid format |
| `401` | YouTube authentication required (no valid refresh token) |
| `413` | Video file too large |

---

### 13.4 Search YouTube Videos

```
GET /youtube/search
```

**Auth Required**: ❌ No (Uses service account OAuth2)
**Roles**: None

#### Query Parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `query` | `string` | βœ… | β€” | Search terms |
| `maxResults` | `integer` | ❌ | `10` | Max number of results (capped at 50) |

#### Response `200 OK`

```json
{
  "success": true,                                              // boolean
  "items": [                                                    // array β€” Search results
    {
      "videoId": "dQw4w9WgXcQ",                                // string β€” YouTube video ID
      "title": "Example Video Title",                           // string β€” Video title
      "description": "Video description...",                    // string β€” Truncated description
      "thumbnail": "https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg",  // string β€” HQ thumbnail URL
      "channelTitle": "Channel Name",                           // string β€” Channel name
      "publishedAt": "2023-01-15T10:30:00Z",                    // string β€” ISO 8601 publish date
      "videoUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ", // string β€” Watch URL
      "embedUrl": "https://www.youtube.com/embed/dQw4w9WgXcQ"   // string β€” Embed URL
    }
  ],
  "totalResults": 1000000,                                      // number β€” Total matching results
  "resultsPerPage": 10                                          // number β€” Results returned
}
```

#### Error Responses

| Status | Description |
|---|---|
| `400` | Invalid query parameters (missing `query`) |

---

### 13.5 Get Video Details by ID

```
GET /youtube/videos/:videoId
```

**Auth Required**: ❌ No (Uses service account OAuth2)
**Roles**: None

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `videoId` | `string` | βœ… | YouTube video ID (e.g. `dQw4w9WgXcQ`) |

#### Response `200 OK` (Found)

```json
{
  "success": true,                                              // boolean
  "video": {                                                    // object β€” Complete video info
    "videoId": "dQw4w9WgXcQ",                                  // string β€” YouTube ID
    "title": "Example Video",                                   // string β€” Title
    "description": "Full video description...",                 // string β€” Full description
    "thumbnail": "https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg",  // string β€” Thumbnail
    "channelId": "UC1234567890",                                // string β€” Channel ID
    "channelTitle": "Channel Name",                             // string β€” Channel name
    "publishedAt": "2023-01-15T10:30:00Z",                      // string β€” Publish date
    "duration": "PT4M33S",                                      // string β€” ISO 8601 duration
    "viewCount": "1000000",                                     // string β€” View count
    "likeCount": "50000",                                       // string β€” Like count
    "commentCount": "2000",                                     // string β€” Comment count
    "privacyStatus": "public",                                  // string β€” "public" | "private" | "unlisted"
    "videoUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",  // string β€” Watch URL
    "embedUrl": "https://www.youtube.com/embed/dQw4w9WgXcQ"     // string β€” Embed URL
  }
}
```

#### Response `200 OK` (Not Found)

```json
{
  "success": false,                       // boolean
  "message": "Video not found"            // string
}
```

> **Note**: Returns `200` with `success: false` when video doesn't exist β€” not a `404`.

---

### 13.6 Get Channel Videos

```
GET /youtube/channel/:channelId/videos
```

**Auth Required**: ❌ No (Uses service account OAuth2)
**Roles**: None

#### Path Parameters

| Parameter | Type | Required | Description |
|---|---|---|---|
| `channelId` | `string` | βœ… | YouTube channel ID (e.g. `UC1234567890`) |

#### Query Parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `maxResults` | `integer` | ❌ | `10` | Max number of results (capped at 50) |

#### Response `200 OK`

```json
{
  "success": true,                                              // boolean
  "items": [                                                    // array β€” Channel videos (newest first)
    {
      "videoId": "dQw4w9WgXcQ",                                // string β€” Video ID
      "title": "Latest Video",                                  // string β€” Title
      "description": "Video description...",                    // string
      "thumbnail": "https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg",  // string
      "publishedAt": "2023-01-15T10:30:00Z",                    // string β€” ISO 8601
      "videoUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ", // string
      "embedUrl": "https://www.youtube.com/embed/dQw4w9WgXcQ"   // string
    }
  ],
  "totalResults": 150,                                          // number β€” Total channel videos
  "resultsPerPage": 10                                          // number β€” Results returned
}
```

#### Error Responses

| Status | Description |
|---|---|
| `404` | Channel not found |

---

## 14. Course Materials Role-Based Access Matrix

| Endpoint | Student | Instructor (assigned) | TA (assigned) | Admin / IT Admin |
|---|---|---|---|---|
| `GET .../materials` | βœ… (published only) | βœ… (all) | βœ… (all) | βœ… (all) |
| `GET .../materials/:id` | βœ… (published only) | βœ… | βœ… | βœ… |
| `POST .../materials` | ❌ | βœ… | βœ… | βœ… |
| `POST .../materials/bulk` | ❌ | βœ… | βœ… | βœ… |
| `POST .../materials/video` | ❌ | βœ… | βœ… | βœ… |
| `POST .../materials/document` | ❌ | βœ… | βœ… | βœ… |
| `PUT .../materials/:id` | ❌ | βœ… (own only) | βœ… (own only) | βœ… (any) |
| `DELETE .../materials/:id` | ❌ | βœ… (own only) | βœ… (own only) | βœ… (any) |
| `PATCH .../materials/:id/visibility` | ❌ | βœ… (own only) | βœ… (own only) | βœ… (any) |
| `GET .../materials/:id/download` | βœ… (published only) | βœ… | βœ… | βœ… |
| `POST .../materials/:id/view` | βœ… | βœ… | βœ… | βœ… |
| `GET .../materials/:id/embed` | βœ… | βœ… | βœ… | βœ… |
| `GET .../structure` | βœ… | βœ… | βœ… | βœ… |
| `GET .../structure/:id` | βœ… | βœ… | βœ… | βœ… |
| `POST .../structure` | ❌ | βœ… | ❌ | βœ… |
| `PUT .../structure/:id` | ❌ | βœ… | ❌ | βœ… |
| `DELETE .../structure/:id` | ❌ | βœ… | ❌ | βœ… |
| `PATCH .../structure/reorder` | ❌ | βœ… | ❌ | βœ… |

---

## 15. Video Lecture Viewing β€” End-to-End Flow

### 15.1 Instructor Uploads a Video Lecture

```mermaid
sequenceDiagram
    participant I as Instructor
    participant API as Backend API
    participant YT as YouTube API
    participant DB as Database

    I->>API: POST /api/courses/1/materials/video (multipart: video + metadata)
    API->>API: Validate user is assigned to course
    API->>YT: Upload video buffer (unlisted)
    YT-->>API: Return { videoId, videoUrl }
    API->>DB: INSERT INTO course_materials (materialType='video', youtubeVideoId, externalUrl=embed URL)
    DB-->>API: Return saved material entity
    API-->>I: 201 { materialId, youtubeVideoId, embedUrl, youtubeUrl }
```

### 15.2 Student Views a Video Lecture

```mermaid
sequenceDiagram
    participant S as Student
    participant API as Backend API
    participant DB as Database

    S->>API: GET /api/courses/1/materials?materialType=video
    API->>DB: SELECT WHERE course_id=1 AND material_type='video' AND is_published=1
    DB-->>API: Return published video materials
    API-->>S: 200 { data: [...], meta: { total, page, limit, totalPages } }
    Note over S: Student selects a video
    S->>API: POST /api/courses/1/materials/5/view
    API->>DB: UPDATE viewCount = viewCount + 1
    API-->>S: 200 { message, materialId, viewCount }
    S->>API: GET /api/courses/1/materials/5/embed
    API-->>S: 200 { videoId, embedUrl, iframeHtml }
    Note over S: Flutter renders YouTube video using embedUrl in WebView/iframe
```

### 15.3 Flutter Integration Example (Video Player)

```dart
// Fetch video material
final response = await dio.get(
  '$baseUrl/api/courses/$courseId/materials/$materialId/embed',
  options: Options(headers: {'Authorization': 'Bearer $token'}),
);

final embedUrl = response.data['embedUrl'] as String;
final videoId = response.data['videoId'] as String;

// Option 1: Use WebView for embedded YouTube
WebViewWidget(controller: WebViewController()
  ..loadRequest(Uri.parse(embedUrl)));

// Option 2: Use youtube_player_flutter package
YoutubePlayer(
  controller: YoutubePlayerController(
    initialVideoId: videoId,
    flags: YoutubePlayerFlags(autoPlay: false),
  ),
);
```

---

## 16. Course Details Handling β€” What Each Role Sees

### 16.1 Course Visibility & Access Per Role

#### **Student View**
- **Course Catalog**: Can browse all courses (public endpoints, no auth required)
- **Course Details** (`GET /api/courses/:id`):
  - Full course information (name, code, description, credits, level)
  - Prerequisites list
  - Available sections count
  - **Cannot see**: Other students' information, unpublished materials
- **Course Materials**:
  - Only **published** materials (`isPublished = true`)
  - Can view videos, download documents, track views
  - **Cannot see**: Draft materials, other students' submissions
- **Assignments**:
  - Only **published** assignments
  - Can submit if enrolled in the course section
  - Can view own submissions and grades
  - **Cannot see**: Other students' submissions
- **Labs**:
  - Only **published** labs
  - Can submit if enrolled (currently **no enrollment check** for labs β€” missing validation)
  - Can view own submissions and grades
  - Can view lab instructions
- **Sections & Schedules**: Can view all sections and schedules (public)

#### **Instructor View**
- **Teaching Courses** (`GET /api/enrollments/teaching`):
  - All sections where instructor is assigned
  - Course details, section info, semester dates
- **Course Details**:
  - Same as student view PLUS:
  - Can create/update/delete courses (if authorized)
  - Can manage sections and schedules
- **Course Materials**:
  - **All materials** (including drafts) for courses they teach
  - Can upload videos to YouTube, documents to Google Drive
  - Can organize materials by weeks using course structure
  - Can update/delete **own** materials only (admins can manage any)
- **Assignments**:
  - Can create/update/publish/close assignments
  - Can view **all submissions** for assignments in their courses
  - Can grade submissions (creates central grade record)
  - Can upload instruction files to Google Drive
- **Labs**:
  - Can create/update/publish/close labs
  - Can add instructions with file attachments
  - Can view **all submissions** and grade them
  - Can mark student attendance
  - Can upload TA materials (answer keys, rubrics)
  - **Can delete** labs

#### **Teaching Assistant (TA) View**
- **Teaching Courses**: Same as instructor (sections where assigned as TA)
- **Course Materials**:
  - **All materials** (including drafts) for courses they're assigned to
  - Can upload/create materials
  - Can update/delete **own** materials only
  - **Cannot** create/update course structure (weeks, lectures organization)
- **Assignments**:
  - Can create/update/delete assignments (same as instructor)
  - Can view all submissions and grade them
  - Can upload instruction files
- **Labs**:
  - Can create/update labs
  - Can add instructions and upload files
  - Can view all submissions and grade them
  - Can mark attendance
  - Can upload TA materials
  - **Cannot delete** labs (only instructors/admins)
- **Sections & Students**:
  - Can view enrolled students in their sections
  - Can view instructor/TA assignments

#### **Admin / IT Admin View**
- **Full Access** to all courses, sections, schedules, materials, assignments, labs
- Can manage any material (not just own)
- Can manage course structure
- Can assign instructors/TAs to sections
- Can manage student enrollments
- Can delete any resource
- IT Admin additionally has system-level access (backup, monitoring, security)

#### **Department Head View**
- **Currently NO specific access** to courses/assignments/labs features
- Only has access to:
  - Schedule templates (`/api/schedule-templates`)
  - Campus events (`/api/campus-events`)
- **Enhancement Needed**: Would need additional endpoints to view department courses overview, instructor assignments, etc.

### 16.2 Course Details Response Fields

When calling `GET /api/courses/:id`, the response includes:

```json
{
  "id": 1,
  "departmentId": 3,
  "name": "Introduction to CS",
  "code": "CS101",
  "description": "Fundamentals of programming...",
  "credits": 3,
  "level": "FRESHMAN",
  "syllabusUrl": "https://example.com/syllabus.pdf",
  "instructorId": 5,                   // ⭐ Primary instructor ID (may be null)
  "taIds": [1, 2],                     // ⭐ Array of TA user IDs (may be null)
  "status": "ACTIVE",
  "createdAt": "2025-01-15T10:00:00Z",
  "updatedAt": "2025-01-15T10:00:00Z",
  "department": {
    "id": 3,
    "name": "Computer Science",
    "code": "CS"
  },
  "prerequisites": [],                 // Array of prerequisite objects
  "sections": [],                      // Array of section objects
  "prerequisitesCount": 0,             // ⭐ Convenience field
  "sectionsCount": 2                   // ⭐ Convenience field
}
```

> **Note**: `instructorId` and `taIds` are stored in the `courses` table but actual section-level instructor/TA assignments are managed separately in `course_instructors` and `course_tas` tables via the enrollments module.

---

## 17. Business Logic Details

### 17.1 Assignment Submission β€” Enrollment Check

**Critical**: Assignment submission (`POST /api/assignments/:id/submit` and `POST /api/assignments/:id/submissions/upload`) **requires** the student to be enrolled in the assignment's course.

```typescript
// Enrollment validation in assignments.service.ts
const enrollment = await this.enrollmentRepo
  .createQueryBuilder('enrollment')
  .innerJoin('course_sections', 'section', 'section.section_id = enrollment.section_id')
  .where('enrollment.user_id = :userId', { userId })
  .andWhere('section.course_id = :courseId', { courseId: assignment.courseId })
  .andWhere('enrollment.enrollment_status = :status', { status: 'enrolled' })
  .getOne();

if (!enrollment) {
  throw new BadRequestException('Student is not enrolled in this course');
}
```

**Business Rules**:
1. Assignment must be in `published` status
2. If `availableFrom` is set, current time must be after it
3. If past `dueDate`:
   - If `lateSubmissionAllowed = false`: Throws `SubmissionDeadlinePassedException`
   - If `lateSubmissionAllowed = true`: Sets `isLate = 1`
4. **Student must be enrolled** in the course's section with status `enrolled`
5. **UPSERT Logic**: 
   - If latest submission is `graded`: Creates new attempt (increment `attemptNumber`)
   - If latest submission is not graded: Updates existing submission

### 17.2 Lab Submission β€” Missing Enrollment Check

**Important**: Lab submission (`POST /api/labs/:id/submit` and `POST /api/labs/:id/submissions/upload`) currently **does NOT check** if the student is enrolled in the course.

```typescript
// labs.service.ts β€” submit() method
// ⚠️ NO enrollment validation found
async submit(labId: number, userId: number, dto: SubmitLabDto): Promise<LabSubmission> {
  const lab = await this.findById(labId);
  
  let isLate = false;
  if (lab.dueDate && new Date() > new Date(lab.dueDate)) {
    isLate = true;
  }
  
  // UPSERT logic...
}
```

**Recommendation**: Add enrollment check similar to assignments for consistency.

### 17.3 Assignment vs Lab Submission Differences

| Feature | Assignments | Labs |
|---|---|---|
| **Late Detection** | `isLate: number` (0 or 1) | `isLate: boolean` (true/false) |
| **Attempt Tracking** | `attemptNumber` auto-incremented | No attempt tracking |
| **UPSERT Behavior** | Updates if not graded, new attempt if graded | Updates existing or creates new |
| **Enrollment Check** | βœ… Required | ❌ Missing (should be added) |
| **Get My Submission** | Returns single latest submission | Returns **array** of all submissions |
| **Submission Types** | `file`, `text`, `link`, `multiple` | `text`, `file` only |
| **Grade Integration** | Creates central grade record | Creates central grade record (only if status=`graded`) |

### 17.4 Grade Integration

Both assignments and labs automatically create records in the central `grades` table when graded:

**Assignment Grading** (`PATCH /api/assignments/:id/submissions/:subId/grade`):
```typescript
await this.gradesService.createGrade({
  userId: submission.userId,
  courseId: assignment.courseId,
  gradeType: GradeType.ASSIGNMENT,
  assignmentId: assignmentId,
  score: dto.score,
  maxScore: Number(assignment.maxScore),
  feedback: dto.feedback,
  isPublished: true,  // Immediately visible
}, graderId);
```

**Lab Grading** (`PATCH /api/labs/:id/submissions/:subId/grade`):
```typescript
// Only creates grade if status is 'graded' and score provided
if (dto.score !== undefined && dto.status === 'graded') {
  await this.gradesService.createGrade({
    userId: submission.userId,
    courseId: lab.courseId,
    gradeType: GradeType.LAB,
    labId: labId,
    score: dto.score,
    maxScore: Number(lab.maxScore),
    feedback: dto.feedback,
    isPublished: true,
  }, graderId);
}
```

### 17.5 Google Drive File Organization

**Assignment Instructions**:
- Folder: `EduVerse/Courses/{CourseCode}/Assignments/Assignment_{ID}/Instructions/`
- File naming: `{Title}_v1.{ext}`

**Assignment Submissions**:
- Folder: `EduVerse/Courses/{CourseCode}/Assignments/Assignment_{ID}/Submissions/User_{UserID}/`
- File naming: `Assignment_{ID}_Submission_{YYYYMMDD}.{ext}`

**Lab Instructions**:
- Folder: `EduVerse/Courses/{CourseCode}/Labs/Lab_{LabNumber}/Instructions/`
- File naming: `{Title}_v1.{ext}`

**Lab TA Materials**:
- Folder: `EduVerse/Courses/{CourseCode}/Labs/Lab_{LabNumber}/TA_Materials/`
- File naming: `{Type}_{Title}.{ext}` (e.g., `solution_Lab_1_Answer_Key.pdf`)

**Lab Submissions**:
- Folder: `EduVerse/Courses/{CourseCode}/Labs/Lab_{LabNumber}/Submissions/User_{UserID}/`
- File naming: `Lab{LabNumber}_Submission_{YYYYMMDD}.{ext}`

### 17.6 Course Section Status Auto-Calculation

Section status is automatically calculated based on enrollment:

```typescript
private calculateSectionStatus(maxCapacity: number, currentEnrollment: number): SectionStatus {
  if (currentEnrollment >= maxCapacity) {
    return SectionStatus.FULL;
  }
  return SectionStatus.OPEN;
}
```

- `OPEN`: Enrollment < Capacity
- `FULL`: Enrollment >= Capacity
- `CLOSED`: Manually set by instructor/admin
- `CANCELLED`: Manually set by instructor/admin

---

## 18. End-to-End Flow Diagrams

### 18.1 Student Course Enrollment Flow

```mermaid
sequenceDiagram
    participant S as Student
    participant API as Backend API
    participant DB as Database

    S->>API: GET /api/enrollments/available
    API->>DB: Query active courses with sections
    DB-->>API: Return courses
    API->>API: Check prerequisites, capacity, conflicts
    API-->>S: 200 { courses with canEnroll flag }
    
    Note over S: Student selects a section
    
    S->>API: POST /api/enrollments/register { sectionId }
    API->>DB: Check prerequisites (grade B- or higher)
    API->>DB: Check schedule conflicts
    API->>DB: Check existing enrollment
    API->>DB: INSERT course_enrollments
    API->>DB: UPDATE sections SET currentEnrollment + 1
    API-->>S: 201 { enrollment details }
```

### 18.2 Assignment Submission Flow (with Enrollment Check)

```mermaid
sequenceDiagram
    participant S as Student
    participant API as Backend API
    participant DB as Database
    participant GD as Google Drive

    S->>API: GET /api/assignments/:id
    API->>DB: Get assignment with course info
    API-->>S: 200 { assignment details }
    
    Note over S: Student prepares submission
    
    S->>API: POST /api/assignments/:id/submissions/upload (multipart)
    API->>DB: Check assignment status = published
    API->>DB: Check availableFrom <= now
    API->>DB: Check dueDate (late detection)
    API->>DB: CHECK enrollment in course section ⭐
    alt Not enrolled
        API-->>S: 400 "Student is not enrolled in this course"
    else Enrolled
        API->>GD: Upload file to student folder
        GD-->>API: Return driveFileId, URLs
        API->>DB: UPSERT submission (check if graded)
        API-->>S: 201 { submission + driveFile }
    end
```

### 18.3 Lab Submission Flow (without Enrollment Check)

```mermaid
sequenceDiagram
    participant S as Student
    participant API as Backend API
    participant DB as Database
    participant GD as Google Drive

    S->>API: GET /api/labs/:id
    API->>DB: Get lab with instructions
    API-->>S: 200 { lab + instructions }
    
    Note over S: Student prepares submission
    
    S->>API: POST /api/labs/:id/submissions/upload (multipart)
    API->>DB: Check lab exists
    API->>DB: Check dueDate (late detection)
    API->>DB: ⚠️ NO enrollment check
    API->>GD: Upload file to student folder
    GD-->>API: Return driveFileId, URLs
    API->>DB: UPSERT submission
    API-->>S: 201 { submission + driveFile }
```

### 18.4 Grading Flow (Central Gradebook Integration)

```mermaid
sequenceDiagram
    participant I as Instructor/TA
    participant API as Backend API
    participant DB as Database
    participant GB as Grades Module

    I->>API: PATCH /api/assignments/:id/submissions/:subId/grade
    API->>DB: Get submission + assignment
    API->>DB: UPDATE submission (status=graded, score, feedback)
    API->>GB: createGrade({ assignment, score, maxScore })
    GB->>DB: INSERT grades (gradeType='assignment', isPublished=true)
    GB-->>API: Return gradeId
    API-->>I: 200 { submissionId, score, maxScore, gradeId }
```

---

## 19. UI Shape for 5 Roles

This section describes the **expected UI structure** for each role based on the backend API capabilities.

### 19.1 Student UI

#### **Dashboard / Home**
- **My Courses**: Grid/list of enrolled courses with:
  - Course name, code, instructor
  - Current grade (if available)
  - Quick links to materials, assignments, labs
- **Upcoming Deadlines**: Assignments and labs due soon
- **Recent Grades**: Latest graded submissions

#### **Course Catalog** (Public)
- Browse all courses by department, level, search
- View course details:
  - Description, credits, prerequisites
  - Available sections with schedules
  - Enroll button (if `canEnroll = true`)

#### **Course Details Page** (Per Course)
- **Tabs**:
  1. **Overview**: Description, syllabus, instructor/TA info
  2. **Materials**: Published videos, documents (organized by weeks)
     - Video player (YouTube embed)
     - Document viewer/download
     - View tracking (analytics for instructor)
  3. **Assignments**: Published assignments list
     - Title, due date, status
     - Submit button β†’ Modal with:
       - Text editor
       - File upload
       - Link input
       - Late warning if past due
     - View submission history with grades/feedback
  4. **Labs**: Published labs list
     - Title, due date, lab number
     - View instructions (with file attachments)
     - Submit button β†’ Modal with:
       - Text/code editor
       - File upload
     - View submission history with grades/feedback
  5. **Grades**: All graded work with scores, feedback, overall grade
  6. **Schedule**: Section schedule (days, times, rooms)

#### **Enrollment Management**
- **My Enrollments**: List of current/past courses
- **Available Courses**: Browse and register (with prerequisites check)
- **Drop Course**: Button with deadline warning

---

### 19.2 Instructor UI

#### **Dashboard / Home**
- **Teaching Courses**: Grid of assigned sections with:
  - Course name, section number
  - Enrollment count
  - Quick stats: pending submissions, upcoming deadlines
- **Recent Activity**: New submissions, recent grading

#### **Course Management** (Per Assigned Section)
- **Tabs**:
  1. **Overview**:
     - Course details (edit if assigned)
     - Section info (capacity, location)
     - Instructor/TA assignments (view only, admin manages)
     - Enrolled students list (with contact info)
  
  2. **Materials**:
     - **All materials** (including drafts)
     - Upload buttons:
       - πŸ“Ή **Upload Video** β†’ YouTube upload modal (title, description, tags, week)
       - πŸ“„ **Upload Document** β†’ Google Drive upload (title, type, week)
     - Organize by weeks (course structure):
       - Create/edit weeks, lectures, sections, labs
       - Drag-and-drop reorder
     - Toggle visibility (publish/draft)
     - View analytics (view count, download count)
  
  3. **Assignments**:
     - List all assignments (draft/published/closed/archived)
     - **Create Assignment** modal:
       - Title, description, instructions
       - Submission type (file/text/link/multiple)
       - Due date, available from date
       - Late submission settings
       - Max score, weight
       - Allowed file types, max size
     - **View Submissions**:
       - Table of all students with:
         - Name, submission time, late flag
         - Status (submitted/graded/returned)
         - Attempt number
         - Grade input (score, feedback)
       - Bulk actions: download all, grade selected
     - **Grade Submission**:
       - Side-by-side view:
         - Left: Student submission (file viewer, text, link)
         - Right: Grade input (score, feedback, status)
  
  4. **Labs**:
     - List all labs (draft/published/closed/archived)
     - **Create Lab** modal:
       - Title, description, lab number
       - Due date, available from
       - Max score, weight
     - **Manage Instructions**:
       - Add steps (markdown text, file attachments)
       - Reorder instructions
       - Upload instruction files to Drive
     - **View Submissions**: Same as assignments
     - **Grade Submissions**: Same as assignments
     - **Attendance**:
       - Student list with attendance status
       - Mark present/absent/excused/late
       - Export attendance
  
  5. **Grades**:
     - Gradebook view with all graded work
     - Assignment grades, lab grades
     - Calculate overall grades
     - Export grades
  
  6. **Schedule**:
     - Section schedules (days, times, rooms)
     - Create/edit schedules with conflict detection
  
  7. **Analytics** (if available):
     - Student engagement (material views, downloads)
     - Grade distribution
     - Submission patterns

---

### 19.3 Teaching Assistant (TA) UI

**Similar to Instructor UI with these differences**:

#### **Restrictions**:
- ❌ **Cannot** delete labs
- ❌ **Cannot** manage course structure (weeks, lectures organization)
- ❌ **Cannot** assign/remove instructors or TAs
- βœ… **Can** create/edit/delete assignments
- βœ… **Can** create/edit labs (but not delete)
- βœ… **Can** grade all submissions
- βœ… **Can** upload instructions and TA materials
- βœ… **Can** mark lab attendance
- βœ… **Can** view all materials (including drafts)

#### **Additional TA-Specific Features**:
- **TA Materials Tab** (in Labs):
  - Upload answer keys, grading rubrics, solutions
  - Visible only to instructors and TAs (not students)
- **Responsibilities View**:
  - Shows assigned duties (e.g., "Grading labs, office hours Mon/Wed")

---

### 19.4 Admin UI

#### **Full System Access**
- All instructor/TA capabilities **without restrictions**
- Can manage **any** material (not just own)
- Can manage course structure
- Can delete any resource

#### **Admin-Specific Features**:

1. **Course Catalog Management**:
   - Create/edit/delete courses
   - Manage prerequisites (with circular dependency detection)
   - Assign departments, instructors, TAs at course level

2. **Section Management**:
   - Create/edit/delete sections
   - Set capacity, location, status
   - Override enrollment counts

3. **Instructor/TA Assignment**:
   - Assign instructors to sections (primary, co_instructor, guest)
   - Assign TAs to sections
   - View all assignments across sections

4. **Enrollment Management**:
   - View all student enrollments
   - Manually enroll/drop students
   - Override drop deadlines
   - Approve retake requests

5. **System Administration**:
   - Manage departments, semesters, programs
   - User management (create, assign roles)
   - System settings, integrations

---

### 19.5 IT Admin UI

**All Admin capabilities PLUS**:

1. **System Monitoring**:
   - Server health, performance metrics
   - Error tracking, alerts
   - SSL certificate status

2. **Database Management**:
   - Backup/restore
   - Database migrations
   - Query performance

3. **Security**:
   - Audit logs
   - IP blocking/unblocking
   - Security settings

4. **Integrations**:
   - Google Drive configuration
   - YouTube API setup
   - Email service configuration

---

### 19.6 Department Head UI

**Current State**: **Minimal access** to courses/assignments/labs

**Currently Available**:
- Schedule templates (create/manage templates)
- Campus events (create/manage events)

**Recommended Enhancements** (not yet implemented):
- Department courses overview
- Instructor assignments per course
- Enrollment statistics
- Department-level analytics

---

## 20. Missing Endpoints & Future Enhancements

### 20.1 Currently Missing Endpoints

1. **Lab Submission Enrollment Check**: Labs should validate student enrollment like assignments do
2. **Department Head Course Access**: Endpoints for department heads to view/manage department courses
3. **Waitlist Management**: Full waitlist table and enrollment logic
4. **Course Copy/Duplicate**: Clone a course with all materials, assignments, labs
5. **Bulk Enrollment**: Admin enroll multiple students at once
6. **Grade Export**: Export grades to CSV/Excel
7. **Assignment/Lab Cloning**: Duplicate for reuse in future semesters
8. **Discussion Forums**: Per-course discussion boards
9. **Announcements**: Course-wide announcements
10. **Notifications**: Push/email notifications for deadlines, grades

### 20.2 Recommended Improvements

1. **Add enrollment check to lab submission** endpoints for consistency
2. **Implement department_head role** permissions for course oversight
3. **Add soft delete** to labs (currently hard delete)
4. **Add attempt tracking** to lab submissions (like assignments)
5. **Implement waitlist** with auto-enrollment when seats open
6. **Add grade curves** and grading policies
7. **Add plagiarism detection** integration
8. **Implement real-time notifications** (WebSockets)
9. **Add course templates** for quick setup
10. **Add analytics dashboard** for instructors (engagement, grade distribution)

---

> **Last Updated**: April 2026
> **Backend Framework**: NestJS (TypeScript)
> **Database**: MySQL with TypeORM
> **File Storage**: Google Drive API
> **Video Storage**: YouTube API (unlisted uploads)
> **Authentication**: JWT with role-based access control