# This file should ensure the existence of records required to run the application in every environment (production,
# development, test). The code here should be idempotent so that it can be executed at any point in every environment.
# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
#
# Example:
#
#   ["Action", "Comedy", "Drama", "Horror"].each do |genre_name|
#     MovieGenre.find_or_create_by!(name: genre_name)
#   end

post_url_sanitisation_rules = [
  { priority: 10,
    source_pattern: '\Ahttps?://youtu\.be/([^/?#]+)(?:[?#].*)?\z',
    replacement: 'https://www.youtube.com/watch?v=\1' },
  { priority: 20,
    source_pattern: '\Ahttps?://(?:www\.|m\.)?youtube\.com/live/([^/?#]+)(?:[?#].*)?\z',
    replacement: 'https://www.youtube.com/watch?v=\1' },
  { priority: 30,
    source_pattern: '\Ahttps?://(?:www\.|m\.)?youtube\.com/shorts/([^/?#]+)(?:[?#].*)?\z',
    replacement: 'https://www.youtube.com/watch?v=\1' },
  { priority: 40,
    source_pattern: '\Ahttps?://(?:www\.|m\.)?youtube\.com/embed/([^/?#]+)(?:[?#].*)?\z',
    replacement: 'https://www.youtube.com/watch?v=\1' },
  { priority: 50,
    source_pattern:
        '\Ahttps?://(?:www\.|m\.)?youtube\.com/watch\?(?:[^#&]+&)*v=([^&#]+)(?:[&#].*)?\z',
    replacement: 'https://www.youtube.com/watch?v=\1' },
  { priority: 60,
    source_pattern: '\Ahttps?://nico\.ms/([^/?#]+)(?:[?#].*)?\z',
    replacement: 'https://www.nicovideo.jp/watch/\1' },
  { priority: 70,
    source_pattern: '\Ahttps?://(?:www\.)?nicovideo\.jp/watch/([^?#/]+)(?:[?#].*)?\z',
    replacement: 'https://www.nicovideo.jp/watch/\1' }
]

post_url_sanitisation_rule_scope = PostUrlSanitisationRule.unscoped

post_url_sanitisation_rules.each do |attributes|
  priority = attributes.fetch(:priority)
  source_pattern = attributes.fetch(:source_pattern)

  next if post_url_sanitisation_rule_scope.exists?(priority:)
  next if post_url_sanitisation_rule_scope.exists?(source_pattern:)

  post_url_sanitisation_rule_scope.create!(attributes)
end

material_sync_source_uri = ENV['MATERIAL_SYNC_SOURCE_URI']
material_sync_source_file_id = ENV['MATERIAL_SYNC_SOURCE_FILE_ID']

if material_sync_source_uri.present? || material_sync_source_file_id.present?
  source = MaterialSyncSource.find_or_initialize_by(
      name: ENV.fetch('MATERIAL_SYNC_SOURCE_NAME', 'Legacy URI material sync'))
  source.assign_attributes(
      source_kind: ENV.fetch('MATERIAL_SYNC_SOURCE_KIND', 'uri'),
      source_uri: material_sync_source_uri,
      source_path: ENV['MATERIAL_SYNC_SOURCE_PATH'],
      source_file_id: material_sync_source_file_id,
      profile: ENV.fetch('MATERIAL_SYNC_SOURCE_PROFILE', 'legacy_drive'),
      enabled: ENV.fetch('MATERIAL_SYNC_SOURCE_ENABLED', 'true') != 'false',
      default_tag_name: ENV['MATERIAL_SYNC_SOURCE_TAG_NAME'],
      export_path_prefix: ENV['MATERIAL_SYNC_EXPORT_PATH_PREFIX'])
  source.save!
end
