-- Add useful community widgets to existing published homepage_main sections.
-- Every INSERT is idempotent so a partial migration can be rerun safely.

INSERT INTO widgets (layout_section_id,type,title,config_json,sort_order,is_enabled,created_at,updated_at)
SELECT ls.id,'top_contributors',NULL,'{"limit":5}',200,1,NOW(),NOW()
FROM layout_sections ls INNER JOIN layouts l ON l.id=ls.layout_id
WHERE l.status='published' AND ls.section_key='homepage_main'
  AND NOT EXISTS (SELECT 1 FROM widgets w WHERE w.layout_section_id=ls.id AND w.type='top_contributors');

INSERT INTO widgets (layout_section_id,type,title,config_json,sort_order,is_enabled,created_at,updated_at)
SELECT ls.id,'most_viewed',NULL,'{"limit":5}',210,1,NOW(),NOW()
FROM layout_sections ls INNER JOIN layouts l ON l.id=ls.layout_id
WHERE l.status='published' AND ls.section_key='homepage_main'
  AND NOT EXISTS (SELECT 1 FROM widgets w WHERE w.layout_section_id=ls.id AND w.type='most_viewed');

INSERT INTO widgets (layout_section_id,type,title,config_json,sort_order,is_enabled,created_at,updated_at)
SELECT ls.id,'most_useful',NULL,'{"limit":5}',220,1,NOW(),NOW()
FROM layout_sections ls INNER JOIN layouts l ON l.id=ls.layout_id
WHERE l.status='published' AND ls.section_key='homepage_main'
  AND NOT EXISTS (SELECT 1 FROM widgets w WHERE w.layout_section_id=ls.id AND w.type='most_useful');

INSERT INTO widgets (layout_section_id,type,title,config_json,sort_order,is_enabled,created_at,updated_at)
SELECT ls.id,'most_answered',NULL,'{"limit":5}',230,1,NOW(),NOW()
FROM layout_sections ls INNER JOIN layouts l ON l.id=ls.layout_id
WHERE l.status='published' AND ls.section_key='homepage_main'
  AND NOT EXISTS (SELECT 1 FROM widgets w WHERE w.layout_section_id=ls.id AND w.type='most_answered');

INSERT INTO widgets (layout_section_id,type,title,config_json,sort_order,is_enabled,created_at,updated_at)
SELECT ls.id,'unanswered',NULL,'{"limit":5}',240,1,NOW(),NOW()
FROM layout_sections ls INNER JOIN layouts l ON l.id=ls.layout_id
WHERE l.status='published' AND ls.section_key='homepage_main'
  AND NOT EXISTS (SELECT 1 FROM widgets w WHERE w.layout_section_id=ls.id AND w.type='unanswered');

INSERT INTO widgets (layout_section_id,type,title,config_json,sort_order,is_enabled,created_at,updated_at)
SELECT ls.id,'active_tags',NULL,'{"limit":10}',250,1,NOW(),NOW()
FROM layout_sections ls INNER JOIN layouts l ON l.id=ls.layout_id
WHERE l.status='published' AND ls.section_key='homepage_main'
  AND NOT EXISTS (SELECT 1 FROM widgets w WHERE w.layout_section_id=ls.id AND w.type='active_tags');

INSERT INTO widgets (layout_section_id,type,title,config_json,sort_order,is_enabled,created_at,updated_at)
SELECT ls.id,'trending',NULL,'{"limit":5}',260,1,NOW(),NOW()
FROM layout_sections ls INNER JOIN layouts l ON l.id=ls.layout_id
WHERE l.status='published' AND ls.section_key='homepage_main'
  AND NOT EXISTS (SELECT 1 FROM widgets w WHERE w.layout_section_id=ls.id AND w.type='trending');
