summaryrefslogtreecommitdiff
path: root/supabase/schema.sql
blob: 147dd8a2b9df0d04240ea927e9ed9e247ad198f9 (plain) (blame)
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
-- asa.news database schema
-- dumped 2026-02-08 from live supabase instance (kbugptrwjnenmgkhdofn)
-- this file is for reference only — migrations are applied via supabase mcp

-- =============================================================================
-- extensions
-- =============================================================================

CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE EXTENSION IF NOT EXISTS moddatetime SCHEMA extensions;
CREATE EXTENSION IF NOT EXISTS pgmq;
CREATE EXTENSION IF NOT EXISTS pg_cron;
CREATE EXTENSION IF NOT EXISTS pgsodium;

-- =============================================================================
-- custom types
-- =============================================================================

CREATE TYPE public.feed_visibility AS ENUM ('public', 'authenticated');
CREATE TYPE public.subscription_tier AS ENUM ('free', 'pro', 'developer');

-- =============================================================================
-- tables
-- =============================================================================

CREATE TABLE public.feeds (
  id uuid NOT NULL DEFAULT gen_random_uuid(),
  url text NOT NULL,
  site_url text,
  title text,
  description text,
  language text,
  feed_type text,
  image_url text,
  visibility feed_visibility NOT NULL DEFAULT 'public'::feed_visibility,
  etag text,
  last_modified text,
  last_fetched_at timestamp with time zone,
  last_fetch_error text,
  last_fetch_error_at timestamp with time zone,
  consecutive_failures integer NOT NULL DEFAULT 0,
  next_fetch_at timestamp with time zone NOT NULL DEFAULT now(),
  fetch_interval_seconds integer NOT NULL DEFAULT 1800,
  subscriber_count integer NOT NULL DEFAULT 0,
  created_at timestamp with time zone NOT NULL DEFAULT now(),
  updated_at timestamp with time zone NOT NULL DEFAULT now()
);

CREATE TABLE public.user_profiles (
  id uuid NOT NULL,
  display_name text,
  tier subscription_tier NOT NULL DEFAULT 'free'::subscription_tier,
  feed_count integer NOT NULL DEFAULT 0,
  folder_count integer NOT NULL DEFAULT 0,
  muted_keyword_count integer NOT NULL DEFAULT 0,
  custom_feed_count integer NOT NULL DEFAULT 0,
  created_at timestamp with time zone NOT NULL DEFAULT now(),
  updated_at timestamp with time zone NOT NULL DEFAULT now(),
  stripe_customer_identifier text,
  stripe_subscription_identifier text,
  stripe_subscription_status text,
  stripe_current_period_end timestamp with time zone,
  highlight_count integer NOT NULL DEFAULT 0,
  webhook_url text,
  webhook_secret text,
  webhook_enabled boolean NOT NULL DEFAULT false,
  webhook_consecutive_failures integer NOT NULL DEFAULT 0
);

CREATE TABLE public.folders (
  id uuid NOT NULL DEFAULT gen_random_uuid(),
  user_id uuid NOT NULL,
  name text NOT NULL,
  position integer NOT NULL DEFAULT 0,
  created_at timestamp with time zone NOT NULL DEFAULT now(),
  updated_at timestamp with time zone NOT NULL DEFAULT now(),
  icon_url text
);

CREATE TABLE public.subscriptions (
  id uuid NOT NULL DEFAULT gen_random_uuid(),
  user_id uuid NOT NULL,
  feed_id uuid NOT NULL,
  folder_id uuid,
  custom_title text,
  position integer NOT NULL DEFAULT 0,
  vault_secret_id uuid,
  created_at timestamp with time zone NOT NULL DEFAULT now(),
  updated_at timestamp with time zone NOT NULL DEFAULT now()
);

CREATE TABLE public.entries (
  id uuid NOT NULL DEFAULT gen_random_uuid(),
  feed_id uuid NOT NULL,
  owner_id uuid,
  guid text NOT NULL,
  url text,
  title text,
  author text,
  summary text,
  content_html text,
  content_text text,
  image_url text,
  published_at timestamp with time zone,
  word_count integer,
  fetched_at timestamp with time zone NOT NULL DEFAULT now(),
  created_at timestamp with time zone NOT NULL DEFAULT now(),
  enclosure_url text,
  enclosure_type text,
  enclosure_length bigint
);

CREATE TABLE public.user_entry_states (
  user_id uuid NOT NULL,
  entry_id uuid NOT NULL,
  read boolean NOT NULL DEFAULT false,
  saved boolean NOT NULL DEFAULT false,
  read_at timestamp with time zone,
  saved_at timestamp with time zone
);

CREATE TABLE public.muted_keywords (
  id uuid NOT NULL DEFAULT gen_random_uuid(),
  user_id uuid NOT NULL,
  keyword text NOT NULL,
  created_at timestamp with time zone NOT NULL DEFAULT now()
);

CREATE TABLE public.custom_feeds (
  id uuid NOT NULL DEFAULT gen_random_uuid(),
  user_id uuid NOT NULL,
  name text NOT NULL,
  query text NOT NULL,
  position integer NOT NULL DEFAULT 0,
  created_at timestamp with time zone NOT NULL DEFAULT now(),
  updated_at timestamp with time zone NOT NULL DEFAULT now(),
  source_folder_id uuid,
  match_mode text NOT NULL DEFAULT 'or'::text,
  icon_url text
);

CREATE TABLE public.shared_entries (
  id uuid NOT NULL DEFAULT gen_random_uuid(),
  user_id uuid NOT NULL,
  entry_id uuid NOT NULL,
  share_token text NOT NULL,
  created_at timestamp with time zone NOT NULL DEFAULT now(),
  expires_at timestamp with time zone,
  note text,
  highlighted_text text,
  highlight_text_offset integer,
  highlight_text_length integer,
  highlight_text_prefix text DEFAULT ''::text,
  highlight_text_suffix text DEFAULT ''::text
);

CREATE TABLE public.user_highlights (
  id uuid NOT NULL DEFAULT gen_random_uuid(),
  user_id uuid NOT NULL,
  entry_id uuid NOT NULL,
  highlighted_text text NOT NULL,
  note text,
  text_offset integer NOT NULL,
  text_length integer NOT NULL,
  text_prefix text NOT NULL DEFAULT ''::text,
  text_suffix text NOT NULL DEFAULT ''::text,
  color text NOT NULL DEFAULT 'yellow'::text,
  created_at timestamp with time zone NOT NULL DEFAULT now()
);

CREATE TABLE public.api_keys (
  id uuid NOT NULL DEFAULT gen_random_uuid(),
  user_id uuid NOT NULL,
  key_hash text NOT NULL,
  key_prefix character(8) NOT NULL,
  label text,
  created_at timestamp with time zone NOT NULL DEFAULT now(),
  last_used_at timestamp with time zone,
  revoked_at timestamp with time zone
);

-- =============================================================================
-- primary keys
-- =============================================================================

ALTER TABLE public.feeds ADD CONSTRAINT feeds_pkey PRIMARY KEY (id);
ALTER TABLE public.user_profiles ADD CONSTRAINT user_profiles_pkey PRIMARY KEY (id);
ALTER TABLE public.folders ADD CONSTRAINT folders_pkey PRIMARY KEY (id);
ALTER TABLE public.subscriptions ADD CONSTRAINT subscriptions_pkey PRIMARY KEY (id);
ALTER TABLE public.entries ADD CONSTRAINT entries_pkey PRIMARY KEY (id);
ALTER TABLE public.user_entry_states ADD CONSTRAINT user_entry_states_pkey PRIMARY KEY (user_id, entry_id);
ALTER TABLE public.muted_keywords ADD CONSTRAINT muted_keywords_pkey PRIMARY KEY (id);
ALTER TABLE public.custom_feeds ADD CONSTRAINT custom_feeds_pkey PRIMARY KEY (id);
ALTER TABLE public.shared_entries ADD CONSTRAINT shared_entries_pkey PRIMARY KEY (id);
ALTER TABLE public.user_highlights ADD CONSTRAINT user_highlights_pkey PRIMARY KEY (id);
ALTER TABLE public.api_keys ADD CONSTRAINT api_keys_pkey PRIMARY KEY (id);

-- =============================================================================
-- unique constraints
-- =============================================================================

ALTER TABLE public.api_keys ADD CONSTRAINT api_keys_key_hash_key UNIQUE (key_hash);
ALTER TABLE public.folders ADD CONSTRAINT folders_user_id_name_key UNIQUE (user_id, name);
ALTER TABLE public.shared_entries ADD CONSTRAINT shared_entries_share_token_key UNIQUE (share_token);
ALTER TABLE public.shared_entries ADD CONSTRAINT shared_entries_user_id_entry_id_key UNIQUE (user_id, entry_id);
ALTER TABLE public.subscriptions ADD CONSTRAINT subscriptions_user_id_feed_id_key UNIQUE (user_id, feed_id);
ALTER TABLE public.user_profiles ADD CONSTRAINT user_profiles_stripe_customer_identifier_key UNIQUE (stripe_customer_identifier);

-- =============================================================================
-- foreign keys
-- =============================================================================

ALTER TABLE public.api_keys ADD CONSTRAINT api_keys_user_id_fkey FOREIGN KEY (user_id) REFERENCES auth.users(id);
ALTER TABLE public.custom_feeds ADD CONSTRAINT custom_feeds_user_id_fkey FOREIGN KEY (user_id) REFERENCES auth.users(id);
ALTER TABLE public.custom_feeds ADD CONSTRAINT custom_feeds_source_folder_id_fkey FOREIGN KEY (source_folder_id) REFERENCES public.folders(id);
ALTER TABLE public.entries ADD CONSTRAINT entries_feed_id_fkey FOREIGN KEY (feed_id) REFERENCES public.feeds(id);
ALTER TABLE public.entries ADD CONSTRAINT entries_owner_id_fkey FOREIGN KEY (owner_id) REFERENCES auth.users(id);
ALTER TABLE public.folders ADD CONSTRAINT folders_user_id_fkey FOREIGN KEY (user_id) REFERENCES auth.users(id);
ALTER TABLE public.muted_keywords ADD CONSTRAINT muted_keywords_user_id_fkey FOREIGN KEY (user_id) REFERENCES auth.users(id);
ALTER TABLE public.shared_entries ADD CONSTRAINT shared_entries_user_id_fkey FOREIGN KEY (user_id) REFERENCES auth.users(id);
ALTER TABLE public.shared_entries ADD CONSTRAINT shared_entries_entry_id_fkey FOREIGN KEY (entry_id) REFERENCES public.entries(id);
ALTER TABLE public.subscriptions ADD CONSTRAINT subscriptions_user_id_fkey FOREIGN KEY (user_id) REFERENCES auth.users(id);
ALTER TABLE public.subscriptions ADD CONSTRAINT subscriptions_feed_id_fkey FOREIGN KEY (feed_id) REFERENCES public.feeds(id);
ALTER TABLE public.subscriptions ADD CONSTRAINT subscriptions_folder_id_fkey FOREIGN KEY (folder_id) REFERENCES public.folders(id);
ALTER TABLE public.user_entry_states ADD CONSTRAINT user_entry_states_user_id_fkey FOREIGN KEY (user_id) REFERENCES auth.users(id);
ALTER TABLE public.user_entry_states ADD CONSTRAINT user_entry_states_entry_id_fkey FOREIGN KEY (entry_id) REFERENCES public.entries(id);
ALTER TABLE public.user_highlights ADD CONSTRAINT user_highlights_user_id_fkey FOREIGN KEY (user_id) REFERENCES auth.users(id);
ALTER TABLE public.user_highlights ADD CONSTRAINT user_highlights_entry_id_fkey FOREIGN KEY (entry_id) REFERENCES public.entries(id);
ALTER TABLE public.user_profiles ADD CONSTRAINT user_profiles_id_fkey FOREIGN KEY (id) REFERENCES auth.users(id);

-- =============================================================================
-- indexes
-- =============================================================================

-- feeds
CREATE UNIQUE INDEX idx_feeds_url_public ON public.feeds USING btree (url) WHERE (visibility = 'public'::feed_visibility);
CREATE INDEX idx_feeds_next_fetch ON public.feeds USING btree (next_fetch_at) WHERE (consecutive_failures < 10);

-- entries
CREATE UNIQUE INDEX idx_entries_dedup_public ON public.entries USING btree (feed_id, guid) WHERE (owner_id IS NULL);
CREATE UNIQUE INDEX idx_entries_dedup_authenticated ON public.entries USING btree (feed_id, owner_id, guid) WHERE (owner_id IS NOT NULL);
CREATE INDEX idx_entries_feed_published ON public.entries USING btree (feed_id, published_at DESC NULLS LAST);
CREATE INDEX idx_entries_published ON public.entries USING btree (published_at DESC NULLS LAST);
CREATE INDEX idx_entries_owner ON public.entries USING btree (owner_id, published_at DESC NULLS LAST) WHERE (owner_id IS NOT NULL);
CREATE INDEX idx_entries_title_trigram ON public.entries USING gin (title gin_trgm_ops);
CREATE INDEX idx_entries_content_trigram ON public.entries USING gin (content_text gin_trgm_ops);

-- subscriptions
CREATE INDEX idx_subscriptions_user ON public.subscriptions USING btree (user_id);
CREATE INDEX idx_subscriptions_feed ON public.subscriptions USING btree (feed_id);
CREATE INDEX idx_subscriptions_folder ON public.subscriptions USING btree (folder_id);

-- user_entry_states
CREATE INDEX idx_user_entry_states_entry ON public.user_entry_states USING btree (entry_id);
CREATE INDEX idx_user_entry_states_read ON public.user_entry_states USING btree (user_id, entry_id) WHERE (read = true);
CREATE INDEX idx_user_entry_states_saved ON public.user_entry_states USING btree (user_id, saved_at DESC) WHERE (saved = true);

-- folders
CREATE INDEX idx_folders_user ON public.folders USING btree (user_id);

-- muted_keywords
CREATE INDEX idx_muted_keywords_user ON public.muted_keywords USING btree (user_id);
CREATE UNIQUE INDEX idx_muted_keywords_user_keyword ON public.muted_keywords USING btree (user_id, lower(keyword));

-- custom_feeds
CREATE INDEX idx_custom_feeds_user ON public.custom_feeds USING btree (user_id);
CREATE INDEX idx_custom_feeds_source_folder ON public.custom_feeds USING btree (source_folder_id);

-- shared_entries
CREATE INDEX idx_shared_entries_entry ON public.shared_entries USING btree (entry_id);

-- user_highlights
CREATE INDEX user_highlights_user_entry_idx ON public.user_highlights USING btree (user_id, entry_id);
CREATE INDEX user_highlights_user_created_idx ON public.user_highlights USING btree (user_id, created_at DESC);
CREATE INDEX idx_user_highlights_entry ON public.user_highlights USING btree (entry_id);

-- api_keys
CREATE INDEX idx_api_keys_user_id ON public.api_keys USING btree (user_id);
CREATE INDEX idx_api_keys_key_hash ON public.api_keys USING btree (key_hash) WHERE (revoked_at IS NULL);

-- user_profiles
CREATE INDEX idx_user_profiles_stripe_customer ON public.user_profiles USING btree (stripe_customer_identifier) WHERE (stripe_customer_identifier IS NOT NULL);

-- =============================================================================
-- row level security
-- =============================================================================

ALTER TABLE public.api_keys ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.custom_feeds ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.entries ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.feeds ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.folders ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.muted_keywords ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.shared_entries ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.subscriptions ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.user_entry_states ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.user_highlights ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.user_profiles ENABLE ROW LEVEL SECURITY;

-- =============================================================================
-- rls policies
-- =============================================================================

-- api_keys
CREATE POLICY "Users can view own API keys" ON public.api_keys AS PERMISSIVE FOR SELECT USING ((auth.uid() = user_id));
CREATE POLICY "Users can insert own API keys" ON public.api_keys AS PERMISSIVE FOR INSERT WITH CHECK ((auth.uid() = user_id));
CREATE POLICY "Users can update own API keys" ON public.api_keys AS PERMISSIVE FOR UPDATE USING ((auth.uid() = user_id));
CREATE POLICY "Users can delete own API keys" ON public.api_keys AS PERMISSIVE FOR DELETE USING ((auth.uid() = user_id));

-- custom_feeds
CREATE POLICY "users can view own custom feeds" ON public.custom_feeds AS PERMISSIVE FOR SELECT USING ((user_id = (SELECT auth.uid())));
CREATE POLICY "users can insert own custom feeds" ON public.custom_feeds AS PERMISSIVE FOR INSERT WITH CHECK ((user_id = (SELECT auth.uid())));
CREATE POLICY "users can update own custom feeds" ON public.custom_feeds AS PERMISSIVE FOR UPDATE USING ((user_id = (SELECT auth.uid()))) WITH CHECK ((user_id = (SELECT auth.uid())));
CREATE POLICY "users can delete own custom feeds" ON public.custom_feeds AS PERMISSIVE FOR DELETE USING ((user_id = (SELECT auth.uid())));

-- entries
CREATE POLICY "users can view entries from subscribed public feeds" ON public.entries AS PERMISSIVE FOR SELECT
  USING ((
    (owner_id IS NULL AND EXISTS (SELECT 1 FROM subscriptions s WHERE s.feed_id = entries.feed_id AND s.user_id = (SELECT auth.uid())))
    OR (owner_id = (SELECT auth.uid()))
  ));

-- feeds
CREATE POLICY "users can view accessible feeds" ON public.feeds AS PERMISSIVE FOR SELECT
  USING ((
    (visibility = 'public'::feed_visibility AND (SELECT auth.role()) = 'authenticated')
    OR (visibility = 'authenticated'::feed_visibility AND EXISTS (SELECT 1 FROM subscriptions s WHERE s.feed_id = feeds.id AND s.user_id = (SELECT auth.uid())))
  ));

-- folders
CREATE POLICY "users can view own folders" ON public.folders AS PERMISSIVE FOR SELECT USING ((user_id = (SELECT auth.uid())));
CREATE POLICY "users can insert own folders" ON public.folders AS PERMISSIVE FOR INSERT WITH CHECK ((user_id = (SELECT auth.uid())));
CREATE POLICY "users can update own folders" ON public.folders AS PERMISSIVE FOR UPDATE USING ((user_id = (SELECT auth.uid()))) WITH CHECK ((user_id = (SELECT auth.uid())));
CREATE POLICY "users can delete own folders" ON public.folders AS PERMISSIVE FOR DELETE USING ((user_id = (SELECT auth.uid())));

-- muted_keywords
CREATE POLICY "users can view own muted keywords" ON public.muted_keywords AS PERMISSIVE FOR SELECT USING ((user_id = (SELECT auth.uid())));
CREATE POLICY "users can insert own muted keywords" ON public.muted_keywords AS PERMISSIVE FOR INSERT WITH CHECK ((user_id = (SELECT auth.uid())));
CREATE POLICY "users can delete own muted keywords" ON public.muted_keywords AS PERMISSIVE FOR DELETE USING ((user_id = (SELECT auth.uid())));

-- shared_entries
CREATE POLICY "authenticated users can view own shared entries" ON public.shared_entries AS PERMISSIVE FOR SELECT TO authenticated USING ((user_id = (SELECT auth.uid())));
CREATE POLICY "owners can insert own shared entries" ON public.shared_entries AS PERMISSIVE FOR INSERT WITH CHECK ((user_id = (SELECT auth.uid())));
CREATE POLICY "owners can update own shared entries" ON public.shared_entries AS PERMISSIVE FOR UPDATE USING ((user_id = (SELECT auth.uid()))) WITH CHECK ((user_id = (SELECT auth.uid())));
CREATE POLICY "owners can delete own shared entries" ON public.shared_entries AS PERMISSIVE FOR DELETE USING ((user_id = (SELECT auth.uid())));

-- subscriptions
CREATE POLICY "users can view own subscriptions" ON public.subscriptions AS PERMISSIVE FOR SELECT USING ((user_id = (SELECT auth.uid())));
CREATE POLICY "users can insert own subscriptions" ON public.subscriptions AS PERMISSIVE FOR INSERT WITH CHECK ((user_id = (SELECT auth.uid())));
CREATE POLICY "users can update own subscriptions" ON public.subscriptions AS PERMISSIVE FOR UPDATE USING ((user_id = (SELECT auth.uid()))) WITH CHECK ((user_id = (SELECT auth.uid())));
CREATE POLICY "users can delete own subscriptions" ON public.subscriptions AS PERMISSIVE FOR DELETE USING ((user_id = (SELECT auth.uid())));

-- user_entry_states
CREATE POLICY "users can manage own entry states" ON public.user_entry_states AS PERMISSIVE FOR ALL USING ((user_id = (SELECT auth.uid()))) WITH CHECK ((user_id = (SELECT auth.uid())));

-- user_highlights
CREATE POLICY "users can view own highlights" ON public.user_highlights AS PERMISSIVE FOR SELECT USING ((user_id = (SELECT auth.uid())));
CREATE POLICY "users can insert own highlights" ON public.user_highlights AS PERMISSIVE FOR INSERT WITH CHECK ((user_id = (SELECT auth.uid())));
CREATE POLICY "users can update own highlights" ON public.user_highlights AS PERMISSIVE FOR UPDATE USING ((user_id = (SELECT auth.uid()))) WITH CHECK ((user_id = (SELECT auth.uid())));
CREATE POLICY "users can delete own highlights" ON public.user_highlights AS PERMISSIVE FOR DELETE USING ((user_id = (SELECT auth.uid())));

-- user_profiles
CREATE POLICY "users can view own profile" ON public.user_profiles AS PERMISSIVE FOR SELECT USING ((id = (SELECT auth.uid())));
CREATE POLICY "users can update own profile" ON public.user_profiles AS PERMISSIVE FOR UPDATE USING ((id = (SELECT auth.uid()))) WITH CHECK ((id = (SELECT auth.uid())));

-- =============================================================================
-- functions
-- =============================================================================

CREATE OR REPLACE FUNCTION public.handle_new_user()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO ''
AS $function$
begin
  insert into public.user_profiles (id, display_name)
  values (new.id, coalesce(new.raw_user_meta_data ->> 'display_name', split_part(new.email, '@', 1)));

  return new;
end;
$function$;

CREATE OR REPLACE FUNCTION public.subscribe_to_feed(feed_url text, target_folder_id uuid DEFAULT NULL::uuid, feed_custom_title text DEFAULT NULL::text, feed_credential text DEFAULT NULL::text, feed_auth_type text DEFAULT 'bearer'::text)
 RETURNS uuid
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO ''
AS $function$
declare
  resolved_feed_id uuid;
  new_subscription_id uuid;
  resolved_vault_id uuid;
  resolved_visibility public.feed_visibility;
  existing_subscription_id uuid;
begin
  if feed_credential is not null and feed_auth_type not in ('bearer', 'basic', 'query_param') then
    raise exception 'Invalid authentication type: %. Must be bearer, basic, or query_param', feed_auth_type;
  end if;

  if feed_credential is not null then
    resolved_visibility := 'authenticated';
  else
    resolved_visibility := 'public';
  end if;

  if resolved_visibility = 'public' then
    select id into resolved_feed_id
    from public.feeds
    where url = feed_url and visibility = 'public';

    if resolved_feed_id is null then
      insert into public.feeds (url, visibility)
      values (feed_url, 'public')
      returning id into resolved_feed_id;
    end if;

    select id into existing_subscription_id
    from public.subscriptions
    where user_id = auth.uid() and feed_id = resolved_feed_id;

    if existing_subscription_id is not null then
      raise exception 'You are already subscribed to this feed';
    end if;
  else
    insert into public.feeds (url, visibility, fetch_interval_seconds)
    values (feed_url, 'authenticated', 300)
    returning id into resolved_feed_id;

    resolved_vault_id := vault.create_secret(
      jsonb_build_object(
        'authenticationType', feed_auth_type,
        'authenticationValue', feed_credential
      )::text,
      'feed_credential_' || resolved_feed_id::text,
      'Credential for authenticated feed'
    );
  end if;

  insert into public.subscriptions (user_id, feed_id, folder_id, custom_title, vault_secret_id)
  values (auth.uid(), resolved_feed_id, target_folder_id, feed_custom_title, resolved_vault_id)
  returning id into new_subscription_id;

  return new_subscription_id;
end;
$function$;

CREATE OR REPLACE FUNCTION public.update_feed_credentials(p_feed_id uuid, p_auth_type text, p_credential text)
 RETURNS void
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO ''
AS $function$
declare
  v_vault_secret_id uuid;
begin
  if p_auth_type not in ('bearer', 'basic', 'query_param') then
    raise exception 'Invalid authentication type: %. Must be bearer, basic, or query_param', p_auth_type;
  end if;

  select s.vault_secret_id into v_vault_secret_id
  from public.subscriptions s
  where s.feed_id = p_feed_id and s.user_id = auth.uid();

  if v_vault_secret_id is null then
    raise exception 'No authenticated subscription found for this feed';
  end if;

  perform vault.update_secret(
    v_vault_secret_id,
    jsonb_build_object(
      'authenticationType', p_auth_type,
      'authenticationValue', p_credential
    )::text
  );
end;
$function$;

CREATE OR REPLACE FUNCTION public.add_feed_credentials(p_subscription_id uuid, p_auth_type text, p_credential text)
 RETURNS void
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO ''
AS $function$
declare
  v_old_feed_id uuid;
  v_feed_url text;
  v_new_feed_id uuid;
  v_vault_secret_id uuid;
begin
  if p_auth_type not in ('bearer', 'basic', 'query_param') then
    raise exception 'Invalid authentication type: %. Must be bearer, basic, or query_param', p_auth_type;
  end if;

  select s.feed_id into v_old_feed_id
  from public.subscriptions s
  where s.id = p_subscription_id and s.user_id = auth.uid();

  if v_old_feed_id is null then
    raise exception 'Subscription not found';
  end if;

  select f.url into v_feed_url
  from public.feeds f
  where f.id = v_old_feed_id;

  insert into public.feeds (url, visibility, fetch_interval_seconds)
  values (v_feed_url, 'authenticated', 300)
  returning id into v_new_feed_id;

  v_vault_secret_id := vault.create_secret(
    jsonb_build_object(
      'authenticationType', p_auth_type,
      'authenticationValue', p_credential
    )::text,
    'feed_credential_' || v_new_feed_id::text,
    'Credential for authenticated feed'
  );

  update public.subscriptions
  set feed_id = v_new_feed_id, vault_secret_id = v_vault_secret_id
  where id = p_subscription_id;

  update public.feeds
  set subscriber_count = subscriber_count + 1
  where id = v_new_feed_id;

  update public.feeds
  set subscriber_count = greatest(subscriber_count - 1, 0)
  where id = v_old_feed_id;
end;
$function$;

CREATE OR REPLACE FUNCTION public.update_feed_url(target_feed_id uuid, new_url text)
 RETURNS void
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO ''
AS $function$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM public.subscriptions
    WHERE feed_id = target_feed_id
    AND user_id = auth.uid()
  ) THEN
    RAISE EXCEPTION 'not subscribed to this feed';
  END IF;

  UPDATE public.feeds SET url = new_url WHERE id = target_feed_id;
END;
$function$;

CREATE OR REPLACE FUNCTION public.get_timeline(target_folder_id uuid DEFAULT NULL::uuid, target_feed_id uuid DEFAULT NULL::uuid, result_limit integer DEFAULT 50, pagination_cursor timestamp with time zone DEFAULT NULL::timestamp with time zone, unread_only boolean DEFAULT false)
 RETURNS TABLE(entry_id uuid, feed_id uuid, feed_title text, custom_title text, entry_title text, entry_url text, author text, summary text, image_url text, published_at timestamp with time zone, is_read boolean, is_saved boolean, enclosure_url text, enclosure_type text)
 LANGUAGE sql
 STABLE SECURITY DEFINER
 SET search_path TO ''
AS $function$
  SELECT
    e.id AS entry_id,
    e.feed_id,
    f.title AS feed_title,
    s.custom_title,
    e.title AS entry_title,
    e.url AS entry_url,
    e.author,
    e.summary,
    e.image_url,
    e.published_at,
    COALESCE(ues.read, false) AS is_read,
    COALESCE(ues.saved, false) AS is_saved,
    e.enclosure_url,
    e.enclosure_type
  FROM public.entries e
  INNER JOIN public.subscriptions s
    ON s.feed_id = e.feed_id AND s.user_id = auth.uid()
  INNER JOIN public.feeds f ON f.id = e.feed_id
  LEFT JOIN public.user_entry_states ues
    ON ues.entry_id = e.id AND ues.user_id = auth.uid()
  WHERE
    (e.owner_id IS NULL OR e.owner_id = auth.uid())
    AND (target_folder_id IS NULL OR s.folder_id = target_folder_id)
    AND (target_feed_id IS NULL OR e.feed_id = target_feed_id)
    AND (pagination_cursor IS NULL OR e.published_at < pagination_cursor)
    AND (NOT unread_only OR COALESCE(ues.read, false) = false)
    AND NOT EXISTS (
      SELECT 1 FROM public.muted_keywords mk
      WHERE mk.user_id = auth.uid()
      AND (
        e.title ILIKE '%' || mk.keyword || '%'
        OR e.summary ILIKE '%' || mk.keyword || '%'
      )
    )
    AND (
      (SELECT tier FROM public.user_profiles WHERE id = auth.uid()) = 'pro'
      OR e.published_at >= now() - interval '14 days'
    )
  ORDER BY e.published_at DESC NULLS LAST
  LIMIT result_limit;
$function$;

CREATE OR REPLACE FUNCTION public.get_custom_feed(target_custom_feed_id uuid, result_limit integer DEFAULT 50, pagination_cursor timestamp with time zone DEFAULT NULL::timestamp with time zone)
 RETURNS TABLE(entry_id uuid, feed_id uuid, feed_title text, entry_title text, entry_url text, author text, summary text, published_at timestamp with time zone, is_read boolean, is_saved boolean)
 LANGUAGE sql
 STABLE SECURITY DEFINER
 SET search_path TO ''
AS $function$
  select
    e.id, e.feed_id, f.title, e.title, e.url, e.author, e.summary,
    e.published_at,
    coalesce(ues.read, false),
    coalesce(ues.saved, false)
  from public.entries e
  inner join public.subscriptions s
    on s.feed_id = e.feed_id and s.user_id = auth.uid()
  inner join public.feeds f on f.id = e.feed_id
  inner join public.custom_feeds cf on cf.id = target_custom_feed_id and cf.user_id = auth.uid()
  left join public.user_entry_states ues
    on ues.entry_id = e.id and ues.user_id = auth.uid()
  where
    (e.owner_id is null or e.owner_id = auth.uid())
    and (pagination_cursor is null or e.published_at < pagination_cursor)
    and (
      e.title ilike '%' || cf.query || '%'
      or e.summary ilike '%' || cf.query || '%'
      or e.content_text ilike '%' || cf.query || '%'
    )
  order by e.published_at desc nulls last
  limit result_limit;
$function$;

CREATE OR REPLACE FUNCTION public.get_custom_feed_timeline(p_custom_feed_id uuid, p_result_limit integer DEFAULT 50, p_pagination_cursor timestamp with time zone DEFAULT NULL::timestamp with time zone)
 RETURNS TABLE(entry_id uuid, feed_id uuid, feed_title text, custom_title text, entry_title text, entry_url text, author text, summary text, image_url text, published_at timestamp with time zone, is_read boolean, is_saved boolean, enclosure_url text, enclosure_type text)
 LANGUAGE plpgsql
 STABLE SECURITY DEFINER
 SET search_path TO ''
AS $function$
DECLARE
  v_query TEXT;
  v_match_mode TEXT;
  v_source_folder_id UUID;
  v_keywords TEXT[];
  v_user_id UUID := auth.uid();
  v_user_tier public.subscription_tier;
BEGIN
  SELECT cf.query, cf.match_mode, cf.source_folder_id
  INTO v_query, v_match_mode, v_source_folder_id
  FROM public.custom_feeds cf
  WHERE cf.id = p_custom_feed_id AND cf.user_id = v_user_id;

  IF NOT FOUND THEN
    RETURN;
  END IF;

  SELECT tier INTO v_user_tier FROM public.user_profiles WHERE id = v_user_id;

  v_keywords := string_to_array(lower(v_query), ' ');

  RETURN QUERY
  SELECT
    e.id AS entry_id,
    e.feed_id,
    f.title AS feed_title,
    s.custom_title,
    e.title AS entry_title,
    e.url AS entry_url,
    e.author,
    e.summary,
    e.image_url,
    e.published_at,
    COALESCE(ues.read, false) AS is_read,
    COALESCE(ues.saved, false) AS is_saved,
    e.enclosure_url,
    e.enclosure_type
  FROM public.entries e
  INNER JOIN public.subscriptions s
    ON s.feed_id = e.feed_id AND s.user_id = v_user_id
  INNER JOIN public.feeds f ON f.id = e.feed_id
  LEFT JOIN public.user_entry_states ues
    ON ues.entry_id = e.id AND ues.user_id = v_user_id
  WHERE
    (e.owner_id IS NULL OR e.owner_id = v_user_id)
    AND (v_source_folder_id IS NULL OR s.folder_id = v_source_folder_id)
    AND (p_pagination_cursor IS NULL OR e.published_at < p_pagination_cursor)
    AND (
      CASE WHEN v_match_mode = 'and' THEN
        (SELECT bool_and(
          lower(COALESCE(e.title, '') || ' ' || COALESCE(e.summary, ''))
            LIKE '%' || replace(replace(replace(kw, '\', '\\'), '%', '\%'), '_', '\_') || '%' ESCAPE '\'
        ) FROM unnest(v_keywords) AS kw)
      ELSE
        (SELECT bool_or(
          lower(COALESCE(e.title, '') || ' ' || COALESCE(e.summary, ''))
            LIKE '%' || replace(replace(replace(kw, '\', '\\'), '%', '\%'), '_', '\_') || '%' ESCAPE '\'
        ) FROM unnest(v_keywords) AS kw)
      END
    )
    AND NOT EXISTS (
      SELECT 1 FROM public.muted_keywords mk
      WHERE mk.user_id = v_user_id
      AND (
        e.title ILIKE '%' || replace(replace(replace(mk.keyword, '\', '\\'), '%', '\%'), '_', '\_') || '%' ESCAPE '\'
        OR e.summary ILIKE '%' || replace(replace(replace(mk.keyword, '\', '\\'), '%', '\%'), '_', '\_') || '%' ESCAPE '\'
      )
    )
    AND (
      v_user_tier IN ('pro', 'developer')
      OR e.published_at >= now() - interval '14 days'
    )
  ORDER BY e.published_at DESC NULLS LAST
  LIMIT p_result_limit;
END;
$function$;

CREATE OR REPLACE FUNCTION public.get_unread_counts()
 RETURNS TABLE(feed_id uuid, unread_count bigint)
 LANGUAGE sql
 STABLE SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
  SELECT e.feed_id, COUNT(*) AS unread_count
  FROM entries e
  INNER JOIN subscriptions s ON s.feed_id = e.feed_id AND s.user_id = auth.uid()
  WHERE NOT EXISTS (
    SELECT 1 FROM user_entry_states ues
    WHERE ues.entry_id = e.id
      AND ues.user_id = auth.uid()
      AND ues.read = true
  )
  GROUP BY e.feed_id;
$function$;

CREATE OR REPLACE FUNCTION public.mark_all_as_read(p_feed_id uuid DEFAULT NULL::uuid, p_folder_id uuid DEFAULT NULL::uuid, p_read_state boolean DEFAULT true)
 RETURNS bigint
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
DECLARE
  affected_count bigint;
BEGIN
  IF p_read_state THEN
    INSERT INTO user_entry_states (user_id, entry_id, read, saved)
    SELECT auth.uid(), e.id, true, false
    FROM entries e
    INNER JOIN subscriptions s ON s.feed_id = e.feed_id AND s.user_id = auth.uid()
    LEFT JOIN user_entry_states ues ON ues.entry_id = e.id AND ues.user_id = auth.uid()
    WHERE (ues.read IS NULL OR ues.read = false)
      AND (p_feed_id IS NULL OR e.feed_id = p_feed_id)
      AND (p_folder_id IS NULL OR s.folder_id = p_folder_id)
    ON CONFLICT (user_id, entry_id)
    DO UPDATE SET read = true;
  ELSE
    UPDATE user_entry_states
    SET read = false
    WHERE user_id = auth.uid()
      AND read = true
      AND entry_id IN (
        SELECT e.id
        FROM entries e
        INNER JOIN subscriptions s ON s.feed_id = e.feed_id AND s.user_id = auth.uid()
        WHERE (p_feed_id IS NULL OR e.feed_id = p_feed_id)
          AND (p_folder_id IS NULL OR s.folder_id = p_folder_id)
      );
  END IF;

  GET DIAGNOSTICS affected_count = ROW_COUNT;
  RETURN affected_count;
END;
$function$;

CREATE OR REPLACE FUNCTION public.search_entries(p_query text, p_result_limit integer DEFAULT 30)
 RETURNS TABLE(entry_id uuid, feed_id uuid, feed_title text, custom_title text, entry_title text, entry_url text, author text, summary text, image_url text, published_at timestamp with time zone, is_read boolean, is_saved boolean)
 LANGUAGE sql
 STABLE SECURITY DEFINER
 SET search_path TO ''
AS $function$
  SELECT
    e.id AS entry_id,
    e.feed_id,
    COALESCE(f.title, '') AS feed_title,
    s.custom_title,
    COALESCE(e.title, '') AS entry_title,
    COALESCE(e.url, '') AS entry_url,
    e.author,
    e.summary,
    e.image_url,
    e.published_at,
    COALESCE(ues.read, false) AS is_read,
    COALESCE(ues.saved, false) AS is_saved
  FROM public.entries e
  INNER JOIN public.subscriptions s ON s.feed_id = e.feed_id AND s.user_id = auth.uid()
  INNER JOIN public.feeds f ON f.id = e.feed_id
  LEFT JOIN public.user_entry_states ues ON ues.entry_id = e.id AND ues.user_id = auth.uid()
  WHERE (
    e.title ILIKE '%' || replace(replace(replace(p_query, '\', '\\'), '%', '\%'), '_', '\_') || '%' ESCAPE '\'
    OR e.summary ILIKE '%' || replace(replace(replace(p_query, '\', '\\'), '%', '\%'), '_', '\_') || '%' ESCAPE '\'
    OR e.author ILIKE '%' || replace(replace(replace(p_query, '\', '\\'), '%', '\%'), '_', '\_') || '%' ESCAPE '\'
  )
  AND (
    (SELECT tier FROM public.user_profiles WHERE id = auth.uid()) IN ('pro', 'developer')
    OR e.published_at >= now() - interval '14 days'
  )
  ORDER BY e.published_at DESC
  LIMIT p_result_limit;
$function$;

CREATE OR REPLACE FUNCTION public.request_feed_refresh(target_subscription_id uuid)
 RETURNS void
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO ''
AS $function$
declare
  resolved_feed_id uuid;
  resolved_tier public.subscription_tier;
begin
  select s.feed_id into resolved_feed_id
  from public.subscriptions s
  where s.id = target_subscription_id and s.user_id = auth.uid();

  if resolved_feed_id is null then
    raise exception 'Subscription not found';
  end if;

  select tier into resolved_tier from public.user_profiles where id = auth.uid();

  if resolved_tier = 'free' then
    raise exception 'Manual feed refresh requires a Pro subscription';
  end if;

  perform pgmq.send(
    'feed_refresh',
    jsonb_build_object(
      'feed_id', resolved_feed_id,
      'user_id', auth.uid(),
      'requested_at', now()
    )
  );
end;
$function$;

CREATE OR REPLACE FUNCTION public.check_subscription_limit()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO ''
AS $function$
declare
  current_tier public.subscription_tier;
  current_count int;
  maximum_allowed int;
  feed_visibility public.feed_visibility;
begin
  select tier, feed_count into current_tier, current_count
  from public.user_profiles where id = new.user_id;

  maximum_allowed := case current_tier when 'free' then 10 when 'pro' then 200 when 'developer' then 500 else 10 end;

  if current_count >= maximum_allowed then
    raise exception 'You have reached the maximum number of feeds for your plan (% on % tier)', maximum_allowed, current_tier;
  end if;

  select visibility into feed_visibility from public.feeds where id = new.feed_id;

  if current_tier = 'free' and feed_visibility = 'authenticated' then
    raise exception 'Authenticated feeds require a Pro subscription';
  end if;

  update public.user_profiles set feed_count = feed_count + 1 where id = new.user_id;

  update public.feeds
  set subscriber_count = subscriber_count + 1
  where id = new.feed_id;

  return new;
end;
$function$;

CREATE OR REPLACE FUNCTION public.check_folder_limit()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO ''
AS $function$
declare
  current_tier public.subscription_tier;
  current_count int;
  maximum_allowed int;
begin
  select tier, folder_count into current_tier, current_count
  from public.user_profiles where id = new.user_id;

  maximum_allowed := case current_tier when 'free' then 3 when 'pro' then 10000 when 'developer' then 10000 else 3 end;

  if current_count >= maximum_allowed then
    raise exception 'You have reached the maximum number of folders for your plan (% on % tier)', maximum_allowed, current_tier;
  end if;

  update public.user_profiles set folder_count = folder_count + 1 where id = new.user_id;

  return new;
end;
$function$;

CREATE OR REPLACE FUNCTION public.check_muted_keyword_limit()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO ''
AS $function$
declare
  current_tier public.subscription_tier;
  current_count int;
  maximum_allowed int;
begin
  select tier, muted_keyword_count into current_tier, current_count
  from public.user_profiles where id = new.user_id;

  maximum_allowed := case current_tier when 'free' then 5 when 'pro' then 10000 when 'developer' then 10000 else 5 end;

  if current_count >= maximum_allowed then
    raise exception 'You have reached the maximum number of muted keywords for your plan (% on % tier)', maximum_allowed, current_tier;
  end if;

  update public.user_profiles set muted_keyword_count = muted_keyword_count + 1 where id = new.user_id;

  return new;
end;
$function$;

CREATE OR REPLACE FUNCTION public.check_custom_feed_limit()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO ''
AS $function$
declare
  current_tier public.subscription_tier;
  current_count int;
  maximum_allowed int;
begin
  select tier, custom_feed_count into current_tier, current_count
  from public.user_profiles where id = new.user_id;

  maximum_allowed := case current_tier when 'free' then 1 when 'pro' then 1000 else 1 end;

  if current_count >= maximum_allowed then
    raise exception 'You have reached the maximum number of custom feeds for your plan (% on % tier)', maximum_allowed, current_tier;
  end if;

  update public.user_profiles set custom_feed_count = custom_feed_count + 1 where id = new.user_id;

  return new;
end;
$function$;

CREATE OR REPLACE FUNCTION public.check_highlight_limit()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
AS $function$
declare
  current_tier public.subscription_tier;
  current_count int;
  maximum_allowed int;
begin
  select tier, highlight_count into current_tier, current_count
  from public.user_profiles where id = new.user_id;

  maximum_allowed := case current_tier when 'free' then 50 when 'pro' then 100000 when 'developer' then 100000 else 50 end;

  if current_count >= maximum_allowed then
    raise exception 'You have reached the maximum number of highlights for your plan (% on % tier)', maximum_allowed, current_tier;
  end if;

  update public.user_profiles set highlight_count = highlight_count + 1 where id = new.user_id;

  return new;
end;
$function$;

CREATE OR REPLACE FUNCTION public.decrement_subscription_count()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO ''
AS $function$
declare
  feed_vis public.feed_visibility;
begin
  update public.user_profiles
  set feed_count = greatest(feed_count - 1, 0)
  where id = old.user_id;

  update public.feeds
  set subscriber_count = greatest(subscriber_count - 1, 0)
  where id = old.feed_id;

  select visibility into feed_vis from public.feeds where id = old.feed_id;

  if feed_vis = 'authenticated' then
    delete from public.entries where feed_id = old.feed_id and owner_id = old.user_id;
    if old.vault_secret_id is not null then
      delete from vault.secrets where id = old.vault_secret_id;
    end if;
    delete from public.feeds where id = old.feed_id;
  end if;

  return old;
end;
$function$;

CREATE OR REPLACE FUNCTION public.decrement_folder_count()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO ''
AS $function$
begin
  update public.user_profiles
  set folder_count = greatest(folder_count - 1, 0)
  where id = old.user_id;

  return old;
end;
$function$;

CREATE OR REPLACE FUNCTION public.decrement_muted_keyword_count()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO ''
AS $function$
begin
  update public.user_profiles
  set muted_keyword_count = greatest(muted_keyword_count - 1, 0)
  where id = old.user_id;

  return old;
end;
$function$;

CREATE OR REPLACE FUNCTION public.decrement_custom_feed_count()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO ''
AS $function$
begin
  update public.user_profiles
  set custom_feed_count = greatest(custom_feed_count - 1, 0)
  where id = old.user_id;

  return old;
end;
$function$;

CREATE OR REPLACE FUNCTION public.decrement_highlight_count()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO ''
AS $function$
begin
  update public.user_profiles
  set highlight_count = greatest(highlight_count - 1, 0)
  where id = old.user_id;

  return old;
end;
$function$;

CREATE OR REPLACE FUNCTION public.enqueue_feed_refresh_on_subscribe()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
AS $function$
BEGIN
  PERFORM pgmq.send('feed_refresh', jsonb_build_object('feed_id', NEW.feed_id));
  RETURN NEW;
END;
$function$;

CREATE OR REPLACE FUNCTION public.prevent_billing_column_modification()
 RETURNS trigger
 LANGUAGE plpgsql
 SET search_path TO 'public'
AS $function$
BEGIN
  IF coalesce(auth.role(), '') != 'service_role' THEN
    IF NEW.tier IS DISTINCT FROM OLD.tier
      OR NEW.stripe_customer_identifier IS DISTINCT FROM OLD.stripe_customer_identifier
      OR NEW.stripe_subscription_identifier IS DISTINCT FROM OLD.stripe_subscription_identifier
      OR NEW.stripe_subscription_status IS DISTINCT FROM OLD.stripe_subscription_status
      OR NEW.stripe_current_period_end IS DISTINCT FROM OLD.stripe_current_period_end
    THEN
      RAISE EXCEPTION 'Billing columns cannot be modified directly';
    END IF;
  END IF;
  RETURN NEW;
END;
$function$;

CREATE OR REPLACE FUNCTION public.cleanup_stale_entries()
 RETURNS integer
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
DECLARE
  deleted_count integer;
BEGIN
  DELETE FROM public.entries
  WHERE published_at < NOW() - INTERVAL '90 days'
    AND id NOT IN (
      SELECT entry_id FROM public.user_entry_states WHERE saved = true
    );
  GET DIAGNOSTICS deleted_count = ROW_COUNT;
  RETURN deleted_count;
END;
$function$;

-- =============================================================================
-- triggers (public tables)
-- =============================================================================

-- feeds
CREATE TRIGGER feeds_updated_at BEFORE UPDATE ON public.feeds FOR EACH ROW EXECUTE FUNCTION moddatetime('updated_at');

-- user_profiles
CREATE TRIGGER prevent_billing_modification BEFORE UPDATE ON public.user_profiles FOR EACH ROW EXECUTE FUNCTION prevent_billing_column_modification();
CREATE TRIGGER user_profiles_updated_at BEFORE UPDATE ON public.user_profiles FOR EACH ROW EXECUTE FUNCTION moddatetime('updated_at');

-- folders
CREATE TRIGGER check_folder_limit_trigger BEFORE INSERT ON public.folders FOR EACH ROW EXECUTE FUNCTION check_folder_limit();
CREATE TRIGGER decrement_folder_count_trigger AFTER DELETE ON public.folders FOR EACH ROW EXECUTE FUNCTION decrement_folder_count();
CREATE TRIGGER folders_updated_at BEFORE UPDATE ON public.folders FOR EACH ROW EXECUTE FUNCTION moddatetime('updated_at');

-- subscriptions
CREATE TRIGGER check_subscription_limit_trigger BEFORE INSERT ON public.subscriptions FOR EACH ROW EXECUTE FUNCTION check_subscription_limit();
CREATE TRIGGER decrement_subscription_count_trigger AFTER DELETE ON public.subscriptions FOR EACH ROW EXECUTE FUNCTION decrement_subscription_count();
CREATE TRIGGER subscriptions_updated_at BEFORE UPDATE ON public.subscriptions FOR EACH ROW EXECUTE FUNCTION moddatetime('updated_at');
CREATE TRIGGER trigger_enqueue_feed_refresh_after_subscribe AFTER INSERT ON public.subscriptions FOR EACH ROW EXECUTE FUNCTION enqueue_feed_refresh_on_subscribe();

-- muted_keywords
CREATE TRIGGER check_muted_keyword_limit_trigger BEFORE INSERT ON public.muted_keywords FOR EACH ROW EXECUTE FUNCTION check_muted_keyword_limit();
CREATE TRIGGER decrement_muted_keyword_count_trigger AFTER DELETE ON public.muted_keywords FOR EACH ROW EXECUTE FUNCTION decrement_muted_keyword_count();

-- custom_feeds
CREATE TRIGGER check_custom_feed_limit_trigger BEFORE INSERT ON public.custom_feeds FOR EACH ROW EXECUTE FUNCTION check_custom_feed_limit();
CREATE TRIGGER decrement_custom_feed_count_trigger AFTER DELETE ON public.custom_feeds FOR EACH ROW EXECUTE FUNCTION decrement_custom_feed_count();
CREATE TRIGGER custom_feeds_updated_at BEFORE UPDATE ON public.custom_feeds FOR EACH ROW EXECUTE FUNCTION moddatetime('updated_at');

-- user_highlights
CREATE TRIGGER check_highlight_limit_trigger BEFORE INSERT ON public.user_highlights FOR EACH ROW EXECUTE FUNCTION check_highlight_limit();
CREATE TRIGGER decrement_highlight_count_trigger AFTER DELETE ON public.user_highlights FOR EACH ROW EXECUTE FUNCTION decrement_highlight_count();

-- =============================================================================
-- triggers (auth schema -- creates user profile on signup)
-- =============================================================================

CREATE TRIGGER on_auth_user_created AFTER INSERT ON auth.users FOR EACH ROW EXECUTE FUNCTION handle_new_user();

-- =============================================================================
-- pg_cron scheduled jobs
-- =============================================================================

-- daily at 3:00 AM UTC: purge old private entries for free-tier users (>14 days)
SELECT cron.schedule('purge-old-private-entries', '0 3 * * *', $$
    delete from public.entries e
    where e.owner_id is not null
      and exists (
        select 1 from public.user_profiles p
        where p.id = e.owner_id
        and p.tier = 'free'
      )
      and e.published_at < now() - interval '14 days';
  $$);

-- daily at 3:00 AM UTC: cleanup stale entries (>90 days, not saved)
SELECT cron.schedule('cleanup-stale-entries', '0 3 * * *', $$SELECT cleanup_stale_entries()$$);

-- daily at 4:00 AM UTC: purge orphaned entries (no subscribers)
SELECT cron.schedule('purge-orphaned-entries', '0 4 * * *', $$
    delete from public.entries e
    where e.owner_id is null
      and not exists (
        select 1 from public.subscriptions s where s.feed_id = e.feed_id
      );
  $$);

-- daily at 4:30 AM UTC: purge orphaned public feeds (0 subscribers, stale >7 days)
SELECT cron.schedule('purge-orphaned-feeds', '30 4 * * *', $$
    delete from public.feeds
    where visibility = 'public'
      and subscriber_count = 0
      and updated_at < now() - interval '7 days';
  $$);