class RecurringOpeningHour < ApplicationRecord
  default_scope { order(:date) }

  attribute :from, :datetime
  attribute :to, :datetime

  def self.create_view
    sql = <<~SQL.squish
      DROP VIEW IF EXISTS recurring_opening_hours;
      CREATE OR REPLACE VIEW recurring_opening_hours AS WITH RECURSIVE t(n) AS (
        VALUES (0)
      UNION ALL
        SELECT n + 1 FROM t WHERE n < 2
      )
      SELECT *, "from"::date AS date FROM (
        SELECT
          n, week_day, open,
          DATE_TRUNC('week', NOW()::date) - '1 days'::interval + "from"::time + (n * '1 weeks'::interval + week_day * '1 days'::interval) AS from,
          DATE_TRUNC('week', NOW()::date) - '1 days'::interval + "to"::time + (n * '1 weeks'::interval + week_day * '1 days'::interval) AS to
        FROM t
        INNER JOIN opening_hours ON TRUE
      ) ss
      WHERE
        "from"::date NOT IN (SELECT date FROM holidays) AND
        open = true
      ORDER BY date
    SQL

    connection.execute(sql)
  end
end
