-- Create a function to sync site_name to seo_settings
CREATE OR REPLACE FUNCTION sync_site_name_to_seo()
RETURNS TRIGGER AS $$
BEGIN
  IF NEW.key = 'site_name' THEN
    UPDATE seo_settings SET site_name = NEW.value, updated_at = NOW();
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- Create a function to sync site_name back to site_settings
CREATE OR REPLACE FUNCTION sync_seo_to_site_name()
RETURNS TRIGGER AS $$
BEGIN
  IF NEW.site_name IS DISTINCT FROM OLD.site_name THEN
    UPDATE site_settings SET value = NEW.site_name, updated_at = NOW() WHERE key = 'site_name';
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- Create triggers
DROP TRIGGER IF EXISTS tr_sync_site_name_to_seo ON site_settings;
CREATE TRIGGER tr_sync_site_name_to_seo
AFTER INSERT OR UPDATE OF value ON site_settings
FOR EACH ROW EXECUTE FUNCTION sync_site_name_to_seo();

DROP TRIGGER IF EXISTS tr_sync_seo_to_site_name ON seo_settings;
CREATE TRIGGER tr_sync_seo_to_site_name
AFTER UPDATE OF site_name ON seo_settings
FOR EACH ROW EXECUTE FUNCTION sync_seo_to_site_name();
