class Coronavirus::SubSection < ApplicationRecord
  self.table_name = "coronavirus_sub_sections"

  belongs_to :page, foreign_key: "coronavirus_page_id"
  validates :title, :content, presence: true
  validates :page, presence: true
  validate :featured_link_must_be_in_content

  def featured_link_must_be_in_content
    if featured_link.present? && !content.include?(featured_link)
      errors.add(:featured_link, "does not exist in accordion content")
    end
  end
end

class Coronavirus::SubSection < ApplicationRecord
  self.table_name = "coronavirus_sub_sections"

  belongs_to :page, foreign_key: "coronavirus_page_id"
  validates :title, :content, presence: true
  validates :page, presence: true
  validate :featured_link_must_be_in_content
  validate :all_structured_content_valid
  after_initialize :populate_structured_content
  attr_reader :structured_content

  def content=(content)
    super.tap { populate_structured_content }
  end

  def featured_link_must_be_in_content
    return if featured_link.blank? || !structured_content

    unless structured_content.links.any? { |l| l.url == featured_link }
      errors.add(:featured_link, "does not exist in accordion content")
    end
  end

private

  def populate_structured_content
    @structured_content = if StructuredContent.parseable?(content)
                            StructuredContent.parse(content)
                          end
  end

  def all_structured_content_valid
    StructuredContent.error_lines(content).each do |line|
      errors.add(:content, "unable to parse markdown: #{line}")
    end
    errors.present?
  end
end

Create structured content when creating a sub section
Create structured content when creating a sub section

This makes it so that structured content is created when a sub section is. It also adds the validation into the sub section model to ensure that the content is valid according to the Structured content. This in turn means that it is impossible for invalid content to be saved to the database.

It also makes it so that when `content` is called on the `SubSection` model the associated `StructuredContent` is updated. This has been achieved by creating a new `content` method on the `SubSection`. It also ensures that that same population is done after the initialisation of the model. This is to make sure that `StructuredContent` always exists and is usable by the Json Presenter later on.

Co-authored-by: Alex Newton <a4a07234de0a205690872ef5d9931abdf491c9ba@digital.cabinet-office.gov.uk>
Co-authored-by: Kevin Dew <d334d31fcac6ab5494e26b93a13c454c9ec1a7b4@digital.cabinet-office.gov.uk>
