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
require_relative "test_helper"

require "minitest/autorun"
require "rack/test"

require_relative "../lib/ketchup/web"

class TestWeb < Minitest::Test
  include Rack::Test::Methods

  def app = Ketchup::Web.app

  def setup
    Ketchup::DB[:tasks].delete
    Ketchup::DB[:series].delete
    Ketchup::DB[:users].delete
  end

  def test_new_series_page
    get "/series/new", {}, auth_headers
    assert last_response.ok?
    assert_includes last_response.body, "New Series"
    assert_includes last_response.body, 'action="/series"'
  end

  def test_root_links_to_new_series
    get "/", {}, auth_headers
    assert last_response.ok?
    assert_includes last_response.body, "/series/new"
  end

  def test_root_shows_empty_state
    get "/", {}, auth_headers
    assert_includes last_response.body, "All caught up!"
  end

  def test_root_shows_overdue_task_in_focus
    create_series(note: "Call Mom", first_due_date: (Date.today - 3).to_s,
                  interval_unit: "week", interval_count: "2")

    get "/", {}, auth_headers
    assert_includes last_response.body, "Call Mom"
    assert_includes last_response.body, "Next up"
  end

  def test_root_shows_upcoming_task_in_agenda
    create_series(note: "Call Mom", first_due_date: Date.today.to_s,
                  interval_unit: "week", interval_count: "2")

    get "/", {}, auth_headers
    assert_includes last_response.body, "Call Mom"
    assert_includes last_response.body, "agenda-day-pill"
  end

  def test_root_only_shows_own_tasks
    create_series(
      note: "Alice task", interval_unit: "week", interval_count: "1",
      first_due_date: (Date.today - 1).to_s,
      headers: auth_headers(login: "alice@example.com"),
    )

    create_series(
      note: "Bob task", interval_unit: "day", interval_count: "1",
      first_due_date: (Date.today - 1).to_s,
      headers: auth_headers(login: "bob@example.com"),
    )

    get "/", {}, auth_headers(login: "alice@example.com")
    assert_includes last_response.body, "Alice task"
    refute_includes last_response.body, "Bob task"
  end

  def test_root_shows_current_user
    get "/", {}, auth_headers
    assert_includes last_response.body, "alice@example.com"
  end

  def test_root_creates_user_record
    get "/", {}, auth_headers(login: "bob@example.com")
    user = Ketchup::DB[:users].first(login: "bob@example.com")
    assert user
  end

  def test_root_requires_auth
    get "/"
    assert_equal 403, last_response.status
  end

  def test_create_series
    create_series(
      note: "Call Mom", interval_unit: "week", interval_count: "2",
      first_due_date: "2026-03-01",
    )
    assert last_response.redirect?

    series = Ketchup::DB[:series].first
    assert_equal "Call Mom", series[:note]
    assert_equal "week", series[:interval_unit]
    assert_equal 2, series[:interval_count]
    assert_includes last_response["Location"], "/series/#{series[:id]}"
  end

  def test_create_series_creates_first_task
    create_series(
      note: "Call Mom", interval_unit: "week", interval_count: "2",
      first_due_date: "2026-03-01",
    )

    series = Ketchup::DB[:series].first
    task = Ketchup::DB[:tasks].first(series_id: series[:id])
    assert_equal Date.new(2026, 3, 1), task[:due_date]
    assert_nil task[:completed_at]
  end

  def test_create_series_belongs_to_current_user
    create_series(
      note: "Dentist", interval_unit: "quarter", interval_count: "1",
      first_due_date: "2026-06-01",
      headers: auth_headers(login: "dave@example.com"),
    )

    series = Ketchup::DB[:series].first
    user = Ketchup::DB[:users].first(login: "dave@example.com")
    assert_equal user[:id], series[:user_id]
  end

  def test_create_series_strips_whitespace
    create_series(
      note: "  Trim me  ", interval_unit: "day", interval_count: "1",
      first_due_date: "2026-03-01",
    )
    assert_equal "Trim me", Ketchup::DB[:series].first[:note]
  end

  def test_create_series_rejects_empty_note
    create_series(
      note: "  ", interval_unit: "day", interval_count: "1",
      first_due_date: "2026-03-01",
    )
    assert_equal 422, last_response.status
    assert_equal 0, Ketchup::DB[:series].count
  end

  def test_create_series_rejects_invalid_interval_unit
    create_series(
      note: "Nope", interval_unit: "fortnight", interval_count: "1",
      first_due_date: "2026-03-01",
    )
    assert_equal 422, last_response.status
    assert_equal 0, Ketchup::DB[:series].count
  end

  def test_create_series_rejects_zero_interval_count
    create_series(
      note: "Nope", interval_unit: "day", interval_count: "0",
      first_due_date: "2026-03-01",
    )
    assert_equal 422, last_response.status
    assert_equal 0, Ketchup::DB[:series].count
  end

  def test_create_series_rejects_invalid_due_date
    create_series(
      note: "Nope", interval_unit: "day", interval_count: "1",
      first_due_date: "not-a-date",
    )
    assert_equal 422, last_response.status
    assert_equal 0, Ketchup::DB[:series].count
    assert_equal 0, Ketchup::DB[:tasks].count
  end

  def test_complete_task
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: (Date.today - 3).to_s)

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    complete_path = "/series/#{series[:id]}/tasks/#{task[:id]}/complete"
    csrf_post complete_path, {}, auth_headers
    assert last_response.redirect?

    assert_equal "/", URI.parse(last_response["Location"]).path

    old_task = Ketchup::DB[:tasks].first(id: task[:id])
    refute_nil old_task[:completed_at]

    new_task = Ketchup::DB[:tasks].where(completed_at: nil).first
    assert_equal Date.today + 14, new_task[:due_date]
  end

  def test_complete_task_advances_by_months
    create_series(note: "Dentist", interval_unit: "month", interval_count: "3",
                  first_due_date: "2026-01-31")

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    csrf_post "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers

    new_task = Ketchup::DB[:tasks].where(completed_at: nil).first
    assert_equal Date.today >> 3, new_task[:due_date]
  end

  def test_complete_task_advances_from_given_date
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: "2026-03-01")

    task = Ketchup::Task.first
    task.complete!(completed_on: Date.new(2026, 4, 1), by: Ketchup::User.first)

    new_task = Ketchup::Task.where(completed_at: nil).first
    assert_equal Date.new(2026, 4, 15), new_task.due_date
  end

  def test_complete_task_requires_own_task
    create_series(
      note: "Alice task", interval_unit: "day", interval_count: "1",
      first_due_date: (Date.today - 1).to_s,
      headers: auth_headers(login: "alice@example.com"),
    )

    task = Ketchup::DB[:tasks].first
    csrf_post "/series/#{Ketchup::DB[:series].first[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers(login: "bob@example.com")
    assert_includes [403, 404], last_response.status
  end

  def test_complete_task_requires_auth
    create_series(note: "Call Mom", interval_unit: "day", interval_count: "1",
                  first_due_date: "2026-03-01")

    task = Ketchup::DB[:tasks].first
    post "/series/#{Ketchup::DB[:series].first[:id]}/tasks/#{task[:id]}/complete"
    assert_equal 403, last_response.status
  end

  def test_create_series_requires_auth
    post "/series", {
      note: "Nope", interval_unit: "day", interval_count: "1",
      first_due_date: "2026-03-01",
    }
    assert_equal 403, last_response.status
  end

  def test_task_card_links_to_series
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: (Date.today - 3).to_s)

    series = Ketchup::DB[:series].first
    get "/", {}, auth_headers
    assert_includes last_response.body, "href=\"/series/#{series[:id]}\""
    assert_includes last_response.body, "Call Mom"
  end

  def test_task_card_has_complete_form
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: (Date.today - 3).to_s)

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    get "/", {}, auth_headers
    assert_includes last_response.body, "action=\"/series/#{series[:id]}/tasks/#{task[:id]}/complete\""
  end

  def test_task_card_has_csrf_token
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: (Date.today - 3).to_s)

    get "/", {}, auth_headers
    assert_includes last_response.body, 'name="_csrf"'
  end

  def test_get_series_page_shows_detail
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: "2026-03-01")

    series = Ketchup::DB[:series].first
    get "/series/#{series[:id]}", {}, auth_headers
    assert last_response.ok?
    assert_includes last_response.body, "Call Mom"
    assert_includes last_response.body, "2 weeks"
  end

  def test_get_series_requires_own_series
    create_series(
      note: "Alice task", interval_unit: "day", interval_count: "1",
      first_due_date: "2026-03-01",
      headers: auth_headers(login: "alice@example.com"),
    )

    series = Ketchup::DB[:series].first
    get "/series/#{series[:id]}", {}, auth_headers(login: "bob@example.com")
    assert_equal 404, last_response.status
  end

  def test_get_series_404_for_nonexistent
    get "/series/999999", {}, auth_headers
    assert_equal 404, last_response.status
  end

  def test_patch_task_saves_note
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "1",
                  first_due_date: (Date.today - 3).to_s)

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    csrf_post "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers

    completed_task = Ketchup::DB[:tasks].first(id: task[:id])
    patch_task series[:id], completed_task[:id], { note: "Called, all good" }
    assert last_response.ok?

    body = JSON.parse(last_response.body)
    assert_equal "Called, all good", body["note"]
    assert_equal "Called, all good", Ketchup::DB[:tasks].first(id: completed_task[:id])[:note]
  end

  def test_patch_task_saves_completed_at
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "1",
                  first_due_date: (Date.today - 3).to_s)

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    csrf_post "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers

    completed_task = Ketchup::DB[:tasks].first(id: task[:id])
    patch_task series[:id], completed_task[:id], { completed_at: "2026-01-15" }
    assert last_response.ok?

    body = JSON.parse(last_response.body)
    assert_equal "2026-01-15", body["completed_at"]
    assert_equal Date.new(2026, 1, 15), Ketchup::DB[:tasks].first(id: completed_task[:id])[:completed_at].to_date
  end

  def test_patch_latest_completed_task_updates_active_due_date
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: "2026-03-01")

    series = Ketchup::DB[:series].first
    task = Ketchup::DB[:tasks].first
    csrf_post "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers

    active_task = Ketchup::DB[:tasks].where(completed_at: nil).first
    original_due = active_task[:due_date]

    # Backdate completion by one week — active due date should shift accordingly
    patch_task series[:id], task[:id], { completed_at: "2026-02-21" }
    assert last_response.ok?

    updated_active = Ketchup::DB[:tasks].first(id: active_task[:id])
    assert_equal Date.new(2026, 3, 7), updated_active[:due_date]
  end

  def test_patch_task_saves_both_note_and_completed_at
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "1",
                  first_due_date: (Date.today - 3).to_s)

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    csrf_post "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers

    completed_task = Ketchup::DB[:tasks].first(id: task[:id])
    patch_task series[:id], completed_task[:id], { note: "Backdated", completed_at: "2026-02-01" }
    assert last_response.ok?

    body = JSON.parse(last_response.body)
    assert_equal "Backdated", body["note"]
    assert_equal "2026-02-01", body["completed_at"]

    updated = Ketchup::DB[:tasks].first(id: completed_task[:id])
    assert_equal "Backdated", updated[:note]
    assert_equal Date.new(2026, 2, 1), updated[:completed_at].to_date
  end

  def test_patch_task_rejects_invalid_completed_at
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "1",
                  first_due_date: (Date.today - 3).to_s)

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    csrf_post "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers

    completed_task = Ketchup::DB[:tasks].first(id: task[:id])
    patch_task series[:id], completed_task[:id], { completed_at: "not-a-date" }
    assert_equal 422, last_response.status
  end

  def test_patch_task_rejects_active_task
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "1",
                  first_due_date: "2026-03-01")

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    patch_task series[:id], task[:id], { note: "nope" }
    assert_equal 422, last_response.status
  end

  def test_patch_task_requires_own_task
    create_series(
      note: "Alice task", interval_unit: "day", interval_count: "1",
      first_due_date: (Date.today - 1).to_s,
      headers: auth_headers(login: "alice@example.com"),
    )

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    csrf_post "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers(login: "alice@example.com")

    completed_task = Ketchup::DB[:tasks].first(id: task[:id])
    patch_task series[:id], completed_task[:id], { note: "hacked" }, login: "bob@example.com"
    assert_equal 404, last_response.status
  end

  def test_patch_series_updates_note
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: "2026-03-01")

    series = Ketchup::DB[:series].first
    patch "/series/#{series[:id]}", { note: "Call Dad" }, auth_headers
    assert last_response.ok?

    body = JSON.parse(last_response.body)
    assert_equal "Call Dad", body["note"]
    assert_equal "Call Dad", Ketchup::DB[:series].first(id: series[:id])[:note]
  end

  def test_patch_series_updates_interval
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: "2026-03-01")

    series = Ketchup::DB[:series].first
    patch "/series/#{series[:id]}", { interval_count: "3", interval_unit: "month" }, auth_headers
    assert last_response.ok?

    body = JSON.parse(last_response.body)
    assert_equal 3, body["interval_count"]
    assert_equal "month", body["interval_unit"]

    updated = Ketchup::DB[:series].first(id: series[:id])
    assert_equal 3, updated[:interval_count]
    assert_equal "month", updated[:interval_unit]
  end

  def test_patch_task_updates_due_date
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: "2026-03-01")

    series = Ketchup::DB[:series].first
    task = Ketchup::DB[:tasks].first(series_id: series[:id])
    patch "/series/#{series[:id]}/tasks/#{task[:id]}",
          JSON.generate(due_date: "2026-04-15"),
          auth_headers.merge("CONTENT_TYPE" => "application/json")
    assert last_response.ok?

    body = JSON.parse(last_response.body)
    assert_equal "2026-04-15", body["due_date"]
    assert_equal Date.new(2026, 4, 15), Ketchup::DB[:tasks].first(id: task[:id])[:due_date]
  end

  def test_patch_task_due_date_rejects_completed_task
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: "2026-03-01")

    series = Ketchup::DB[:series].first
    task = Ketchup::DB[:tasks].first(series_id: series[:id])
    csrf_post "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers

    completed_task = Ketchup::DB[:tasks].first(id: task[:id])
    refute_nil completed_task[:completed_at]

    patch_task series[:id], task[:id], { due_date: "2026-04-15" }
    assert_equal 422, last_response.status
  end

  def test_patch_series_rejects_invalid_interval_unit
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: "2026-03-01")

    series = Ketchup::DB[:series].first
    patch "/series/#{series[:id]}", { interval_unit: "fortnight" }, auth_headers
    assert_equal 422, last_response.status
  end

  def test_patch_series_rejects_zero_interval_count
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: "2026-03-01")

    series = Ketchup::DB[:series].first
    patch "/series/#{series[:id]}", { interval_count: "0" }, auth_headers
    assert_equal 422, last_response.status
  end

  def test_patch_series_requires_own_series
    create_series(
      note: "Alice task", interval_unit: "day", interval_count: "1",
      first_due_date: "2026-03-01",
      headers: auth_headers(login: "alice@example.com"),
    )

    series = Ketchup::DB[:series].first
    patch "/series/#{series[:id]}", { note: "hacked" }, auth_headers(login: "bob@example.com")
    assert_equal 404, last_response.status
  end

  def test_patch_series_ignores_fields_not_provided
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: "2026-03-01")

    series = Ketchup::DB[:series].first
    patch "/series/#{series[:id]}", { note: "Call Dad" }, auth_headers
    assert last_response.ok?

    updated = Ketchup::DB[:series].first(id: series[:id])
    assert_equal "Call Dad", updated[:note]
    assert_equal "week", updated[:interval_unit]
    assert_equal 2, updated[:interval_count]

    task = Ketchup::DB[:tasks].first(series_id: series[:id])
    assert_equal Date.new(2026, 3, 1), task[:due_date]
  end

  def test_get_user_page_shows_settings
    get "/", {}, auth_headers  # create user
    user_id = Ketchup::DB[:users].first(login: "alice@example.com")[:id]

    get "/users/#{user_id}", {}, auth_headers
    assert last_response.ok?
    assert_includes last_response.body, "alice@example.com"
    assert_includes last_response.body, "Settings"
    assert_includes last_response.body, 'name="email"'
  end

  def test_post_user_email
    get "/", {}, auth_headers  # create user
    user_id = Ketchup::DB[:users].first(login: "alice@example.com")[:id]

    get "/users/#{user_id}", {}, auth_headers
    token = last_response.body[/name="_csrf" value="([^"]+)"/, 1]
    post "/users/#{user_id}/email", { "_csrf" => token, email: "alice@example.org" }, auth_headers
    assert last_response.redirect?

    user = Ketchup::DB[:users].first(id: user_id)
    assert_equal "alice@example.org", user[:email]
  end

  def test_post_user_email_clears_empty
    get "/", {}, auth_headers
    user_id = Ketchup::DB[:users].first(login: "alice@example.com")[:id]

    get "/users/#{user_id}", {}, auth_headers
    token = last_response.body[/name="_csrf" value="([^"]+)"/, 1]
    post "/users/#{user_id}/email", { "_csrf" => token, email: "" }, auth_headers

    user = Ketchup::DB[:users].first(id: user_id)
    assert_nil user[:email]
  end

  def test_get_user_rejects_other_user
    get "/", {}, auth_headers  # create alice
    get "/", {}, auth_headers(login: "bob@example.com")  # create bob
    bob_id = Ketchup::DB[:users].first(login: "bob@example.com")[:id]

    get "/users/#{bob_id}", {}, auth_headers
    assert_equal 404, last_response.status
  end

  def test_layout_includes_footer
    get "/", {}, auth_headers
    assert_includes last_response.body, "site-footer"
  end

  def test_header_links_home_and_new
    get "/", {}, auth_headers
    assert_includes last_response.body, 'href="/"'
    assert_includes last_response.body, 'href="/series/new"'
  end

  def test_csrf_rejects_post_without_token
    get "/", {}, auth_headers  # establish session
    post "/series", {
      note: "No token", interval_unit: "day", interval_count: "1",
      first_due_date: "2026-03-01",
    }, auth_headers
    assert_equal 403, last_response.status
  end

  def test_dashboard_shows_most_urgent_in_focus
    create_series(note: "Low urgency", interval_unit: "month", interval_count: "1",
                  first_due_date: (Date.today - 1).to_s)
    create_series(note: "High urgency", interval_unit: "day", interval_count: "1",
                  first_due_date: (Date.today - 10).to_s)

    get "/", {}, auth_headers
    body = last_response.body
    # Focus section (first task card) should be the most urgent
    focus_pos = body.index("Next up")
    high_pos = body.index("High urgency")
    low_pos = body.index("Low urgency")
    assert focus_pos, "Expected Next up section"
    assert high_pos, "Expected High urgency task"
    assert low_pos, "Expected Low urgency task"
    assert high_pos < low_pos, "High urgency should appear before Low urgency"
  end

  def test_dashboard_agenda_shows_week_strip
    get "/", {}, auth_headers
    assert_includes last_response.body, "agenda-week"
  end

  def test_complete_from_dashboard_redirects_home
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: (Date.today - 3).to_s)

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    csrf_post "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers
    assert last_response.redirect?
    assert_equal "/", URI.parse(last_response["Location"]).path
  end

  def test_complete_shows_flash_with_undo
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: (Date.today - 3).to_s)

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    csrf_post "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers

    get "/", {}, auth_headers
    body = last_response.body
    assert last_response.ok?
    assert_includes body, "Completed"
    assert_includes body, "Call Mom"

    # Flash bar structure: data attribute carries the undo path
    undo_path = "/series/#{series[:id]}/tasks/#{task[:id]}/complete"
    assert_includes body, "data-undo-path=\"#{undo_path}\""
    assert_includes body, "flash-undo-btn"
    assert_includes body, "flash-close-btn"

    # Flash toast appears after the main content
    assert_includes body, "site-header"
    assert body.index("flash-bar") > body.index("site-header")

    # Inline script wires up click handlers and removes flash on dismiss
    assert_includes body, "addEventListener"
    assert_includes body, "fetch(path"
    assert_includes body, "bar.remove()"
  end

  def test_complete_flash_without_undo_path
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: (Date.today - 3).to_s)

    # Simulate a flash with no undo_path (message only)
    env "rack.session", {"flash" => {"message" => "Something happened"}}
    get "/", {}, auth_headers
    body = last_response.body
    assert_includes body, "flash-bar"
    assert_includes body, "Something happened"
    assert_includes body, "flash-close-btn"
    refute_includes body, "data-undo-path"
    assert_match(/hidden/, body[/flash-undo-btn[^>]*/])
  end

  def test_flash_is_cleared_after_display
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: (Date.today - 3).to_s)

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    csrf_post "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers

    get "/", {}, auth_headers
    assert_includes last_response.body, "Undo"

    get "/", {}, auth_headers
    refute_includes last_response.body, "flash-bar"
  end

  def test_delete_complete_restores_task
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: (Date.today - 3).to_s)

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    csrf_post "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers

    assert_equal 2, Ketchup::DB[:tasks].where(series_id: series[:id]).count
    refute_nil Ketchup::DB[:tasks].first(id: task[:id])[:completed_at]

    delete "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers
    assert_equal 204, last_response.status

    assert_nil Ketchup::DB[:tasks].first(id: task[:id])[:completed_at]
    assert_equal 1, Ketchup::DB[:tasks].where(series_id: series[:id]).count
  end

  def test_delete_complete_rejects_active_task
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: "2026-03-01")

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    delete "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers
    assert_equal 422, last_response.status
  end

  def test_delete_complete_requires_own_task
    create_series(
      note: "Alice task", interval_unit: "day", interval_count: "1",
      first_due_date: (Date.today - 1).to_s,
      headers: auth_headers(login: "alice@example.com"),
    )

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    csrf_post "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers(login: "alice@example.com")

    delete "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers(login: "bob@example.com")
    assert_includes [403, 404], last_response.status
  end

  def test_archive_series
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: (Date.today - 3).to_s)

    series = Ketchup::DB[:series].first
    archive_series(series[:id])
    assert last_response.redirect?
    assert_equal "/", URI.parse(last_response["Location"]).path

    updated = Ketchup::DB[:series].first(id: series[:id])
    refute_nil updated[:archived_at]
  end

  def test_archive_hides_from_dashboard
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: (Date.today - 3).to_s)

    series = Ketchup::DB[:series].first
    archive_series(series[:id])

    # First request shows the flash; second request clears it.
    get "/", {}, auth_headers
    get "/", {}, auth_headers
    refute_includes last_response.body, "Call Mom"
  end

  def test_archived_series_detail_still_accessible
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: "2026-03-01")

    series = Ketchup::DB[:series].first
    archive_series(series[:id])

    get "/series/#{series[:id]}", {}, auth_headers
    assert last_response.ok?
    assert_includes last_response.body, "Call Mom"
  end

  def test_archive_deletes_active_task
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: (Date.today - 3).to_s)

    series = Ketchup::DB[:series].first
    task = Ketchup::DB[:tasks].first(series_id: series[:id])
    refute_nil task
    assert_nil task[:completed_at]

    archive_series(series[:id])

    assert_nil Ketchup::DB[:tasks].first(id: task[:id])
  end

  def test_archive_requires_own_series
    create_series(
      note: "Alice task", interval_unit: "day", interval_count: "1",
      first_due_date: "2026-03-01",
      headers: auth_headers(login: "alice@example.com"),
    )

    series = Ketchup::DB[:series].first
    archive_series(series[:id], login: "bob@example.com")
    assert_includes [403, 404], last_response.status
  end

  def test_archive_shows_flash_with_undo
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: (Date.today - 3).to_s)

    series = Ketchup::DB[:series].first
    archive_series(series[:id])

    get "/", {}, auth_headers
    body = last_response.body
    assert_includes body, "Archived"
    assert_includes body, "Call Mom"
    assert_includes body, "data-undo-path=\"/series/#{series[:id]}/archive\""
  end

  def test_unarchive_restores_series
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: (Date.today - 3).to_s)

    series = Ketchup::DB[:series].first
    archive_series(series[:id])

    refute_nil Ketchup::DB[:series].first(id: series[:id])[:archived_at]
    assert_nil Ketchup::DB[:tasks].first(series_id: series[:id], completed_at: nil)

    delete "/series/#{series[:id]}/archive", {}, auth_headers
    assert_equal 204, last_response.status

    assert_nil Ketchup::DB[:series].first(id: series[:id])[:archived_at]
    active_task = Ketchup::DB[:tasks].first(series_id: series[:id], completed_at: nil)
    refute_nil active_task
  end

  def test_unarchive_requires_own_series
    create_series(
      note: "Alice task", interval_unit: "day", interval_count: "1",
      first_due_date: "2026-03-01",
      headers: auth_headers(login: "alice@example.com"),
    )

    series = Ketchup::DB[:series].first
    archive_series(series[:id], login: "alice@example.com")

    delete "/series/#{series[:id]}/archive", {}, auth_headers(login: "bob@example.com")
    assert_includes [403, 404], last_response.status
  end

  def test_series_detail_has_archive_button
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: "2026-03-01")

    series = Ketchup::DB[:series].first
    get "/series/#{series[:id]}", {}, auth_headers
    assert_includes last_response.body, "/series/#{series[:id]}/archive"
  end

  # --- Shared series tests ---

  def test_create_shared_series
    create_series(
      note: "Team standup", interval_unit: "week", interval_count: "1",
      first_due_date: "2026-03-01", shared: true,
    )
    assert last_response.redirect?

    series = Ketchup::DB[:series].first
    assert_equal true, series[:shared]
  end

  def test_create_private_series_by_default
    create_series(
      note: "Call Mom", interval_unit: "week", interval_count: "2",
      first_due_date: "2026-03-01",
    )

    series = Ketchup::DB[:series].first
    assert_equal false, series[:shared]
  end

  def test_shared_series_visible_on_other_users_dashboard
    create_series(
      note: "Team standup", interval_unit: "week", interval_count: "1",
      first_due_date: (Date.today - 1).to_s,
      headers: auth_headers(login: "alice@example.com"),
      shared: true,
    )

    get "/", {}, auth_headers(login: "bob@example.com")
    assert_includes last_response.body, "Team standup"
  end

  def test_private_series_invisible_to_other_users
    create_series(
      note: "Secret task", interval_unit: "week", interval_count: "1",
      first_due_date: (Date.today - 1).to_s,
      headers: auth_headers(login: "alice@example.com"),
    )

    get "/", {}, auth_headers(login: "bob@example.com")
    refute_includes last_response.body, "Secret task"
  end

  def test_non_creator_can_complete_shared_series_task
    create_series(
      note: "Team standup", interval_unit: "week", interval_count: "1",
      first_due_date: (Date.today - 1).to_s,
      headers: auth_headers(login: "alice@example.com"),
      shared: true,
    )

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    csrf_post "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers(login: "bob@example.com")
    assert last_response.redirect?

    completed = Ketchup::DB[:tasks].first(id: task[:id])
    refute_nil completed[:completed_at]
    bob = Ketchup::DB[:users].first(login: "bob@example.com")
    assert_equal bob[:id], completed[:completed_by_user_id]
  end

  def test_non_creator_can_edit_shared_series
    create_series(
      note: "Team standup", interval_unit: "week", interval_count: "1",
      first_due_date: "2026-03-01",
      headers: auth_headers(login: "alice@example.com"),
      shared: true,
    )

    series = Ketchup::DB[:series].first
    patch "/series/#{series[:id]}", { note: "Updated standup" }, auth_headers(login: "bob@example.com")
    assert last_response.ok?

    assert_equal "Updated standup", Ketchup::DB[:series].first(id: series[:id])[:note]
  end

  def test_non_creator_can_archive_shared_series
    create_series(
      note: "Team standup", interval_unit: "week", interval_count: "1",
      first_due_date: "2026-03-01",
      headers: auth_headers(login: "alice@example.com"),
      shared: true,
    )

    series = Ketchup::DB[:series].first
    archive_series(series[:id], login: "bob@example.com")
    assert last_response.redirect?

    refute_nil Ketchup::DB[:series].first(id: series[:id])[:archived_at]
  end

  def test_non_creator_can_unarchive_shared_series
    create_series(
      note: "Team standup", interval_unit: "week", interval_count: "1",
      first_due_date: "2026-03-01",
      headers: auth_headers(login: "alice@example.com"),
      shared: true,
    )

    series = Ketchup::DB[:series].first
    archive_series(series[:id], login: "bob@example.com")

    delete "/series/#{series[:id]}/archive", {}, auth_headers(login: "bob@example.com")
    assert_equal 204, last_response.status

    assert_nil Ketchup::DB[:series].first(id: series[:id])[:archived_at]
  end

  def test_non_creator_can_toggle_shared_off
    create_series(
      note: "Team standup", interval_unit: "week", interval_count: "1",
      first_due_date: "2026-03-01",
      headers: auth_headers(login: "alice@example.com"),
      shared: true,
    )

    series = Ketchup::DB[:series].first
    patch "/series/#{series[:id]}", { shared: "0" }, auth_headers(login: "bob@example.com")
    assert last_response.ok?

    assert_equal false, Ketchup::DB[:series].first(id: series[:id])[:shared]
  end

  def test_non_creator_can_view_shared_series_detail
    create_series(
      note: "Team standup", interval_unit: "week", interval_count: "1",
      first_due_date: "2026-03-01",
      headers: auth_headers(login: "alice@example.com"),
      shared: true,
    )

    series = Ketchup::DB[:series].first
    get "/series/#{series[:id]}", {}, auth_headers(login: "bob@example.com")
    assert last_response.ok?
    assert_includes last_response.body, "Team standup"
  end

  def test_non_creator_cannot_view_private_series
    create_series(
      note: "Private", interval_unit: "week", interval_count: "1",
      first_due_date: "2026-03-01",
      headers: auth_headers(login: "alice@example.com"),
    )

    series = Ketchup::DB[:series].first
    get "/series/#{series[:id]}", {}, auth_headers(login: "bob@example.com")
    assert_equal 404, last_response.status
  end

  def test_task_card_shows_shared_icon_for_shared_series
    create_series(
      note: "Team standup", interval_unit: "week", interval_count: "1",
      first_due_date: (Date.today - 1).to_s,
      shared: true,
    )

    get "/", {}, auth_headers
    assert_includes last_response.body, "aria-label=\"Shared\""
  end

  def test_task_card_no_shared_icon_for_private_series
    create_series(
      note: "Private task", interval_unit: "week", interval_count: "1",
      first_due_date: (Date.today - 1).to_s,
    )

    get "/", {}, auth_headers
    refute_includes last_response.body, "aria-label=\"Shared\""
  end

  def test_series_detail_shows_shared_status
    create_series(
      note: "Team standup", interval_unit: "week", interval_count: "1",
      first_due_date: "2026-03-01",
      shared: true,
    )

    series = Ketchup::DB[:series].first
    get "/series/#{series[:id]}", {}, auth_headers
    assert last_response.ok?
    assert_includes last_response.body, "Shared"
  end

  def test_complete_task_records_completed_by
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: (Date.today - 3).to_s)

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    csrf_post "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers

    completed = Ketchup::DB[:tasks].first(id: task[:id])
    user = Ketchup::DB[:users].first(login: "alice@example.com")
    refute_nil completed[:completed_at]
    assert_equal user[:id], completed[:completed_by_user_id]
  end

  def test_undo_complete_clears_completed_by
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: (Date.today - 3).to_s)

    task = Ketchup::DB[:tasks].first
    series = Ketchup::DB[:series].first
    csrf_post "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers

    delete "/series/#{series[:id]}/tasks/#{task[:id]}/complete", {}, auth_headers
    assert_equal 204, last_response.status

    restored = Ketchup::DB[:tasks].first(id: task[:id])
    assert_nil restored[:completed_at]
    assert_nil restored[:completed_by_user_id]
  end

  def test_new_series_page_has_shared_checkbox
    get "/series/new", {}, auth_headers
    assert last_response.ok?
    assert_includes last_response.body, 'name="shared"'
    assert_includes last_response.body, "Shared with everyone"
  end

  def test_patch_series_updates_shared
    create_series(note: "Call Mom", interval_unit: "week", interval_count: "2",
                  first_due_date: "2026-03-01")

    series = Ketchup::DB[:series].first
    patch "/series/#{series[:id]}", { shared: "1" }, auth_headers
    assert last_response.ok?

    assert_equal true, Ketchup::DB[:series].first(id: series[:id])[:shared]
  end

  private

  def csrf_post(path, params = {}, headers = auth_headers)
    get "/", {}, headers
    escaped = Regexp.escape(path)
    token = last_response.body[/action="#{escaped}".*?name="_csrf" value="([^"]+)"/m, 1]
    post path, params.merge("_csrf" => token), headers
  end

  def create_series(note:, interval_unit:, interval_count:, first_due_date:, headers: auth_headers, shared: false)
    get "/series/new", {}, headers  # establish session and get CSRF token
    token = last_response.body[/name="_csrf" value="([^"]+)"/, 1]
    post "/series", {
      _csrf: token,
      note: note, interval_unit: interval_unit, interval_count: interval_count,
      first_due_date: first_due_date,
      shared: shared ? "1" : nil,
    }.compact, headers
  end

  def patch_task(series_id, task_id, data, login: "alice@example.com")
    patch "/series/#{series_id}/tasks/#{task_id}",
      data.to_json,
      auth_headers(login: login).merge("CONTENT_TYPE" => "application/json")
  end

  def archive_series(series_id, login: "alice@example.com")
    headers = auth_headers(login: login)
    get "/series/#{series_id}", {}, headers
    archive_path = "/series/#{series_id}/archive"
    escaped = Regexp.escape(archive_path)
    token = last_response.body[/action="#{escaped}".*?name="_csrf" value="([^"]+)"/m, 1]
    post archive_path, { "_csrf" => token }, headers
  end

  def auth_headers(login: "alice@example.com")
    { "HTTP_REMOTE_USER" => login }
  end
end