module Twitch
  class TeamMembership < Service::Base
    include ActiveModel::Validations::Callbacks

    TRUTHIES = [true, 'true', 1, '1'].freeze

    self.service_endpoint = Settings.roster.endpoint

    attributes :team_id, :channel_id, :revenue_revealed, :stats_revealed

    before_validation :cast_to_bool

    validates :team_id, :channel_id, numericality: { only_integer: true }
    validates :revenue_revealed, :stats_revealed, inclusion: { in: [true, false] }

    def self.find_by_slug(slug)
      team_id, channel_id = slug.split('_')

      where(team_id: team_id).find { |membership| membership.channel_id == channel_id }
    end

    def self.where(team_id:)
      response = get("/v1/teams/#{team_id}/memberships")

      response.body['data'].map { |membership| from_attributes(membership) }
    end

    def destroy
      response = delete("/v1/teams/#{@team_id}/channels/#{@channel_id}/membership")

      unless response.success?
        case response.status
        when 404
          errors.add(:base, :invalid, message: response.body['message'])
        else
          raise "Unexpected response (#{response.status}) when deleting membership"
        end

        return false
      end

      true
    end

    def save
      return false unless valid?

      body = {
        channel_id: @channel_id.to_s,
        revenue_revealed: @revenue_revealed,
        stats_revealed: @stats_revealed
      }

      response = post("/v1/teams/#{@team_id}/memberships", body: body.to_json)

      unless response.success?
        message = response.body['message']

        case response.status
        when 404
          errors.add(:team_id, :invalid, message: message)
        when 422
          errors.add(:base, :invalid, message: message)
        else
          raise "Unexpected response (#{response.status}) when creating membership: #{message}"
        end

        return false
      end

      true
    end

    def slug
      "#{@team_id}_#{@channel_id}"
    end

    def to_param
      slug
    end

    private

    def cast_to_bool
      @revenue_revealed = TRUTHIES.include?(@revenue_revealed)
      @stats_revealed = TRUTHIES.include?(@stats_revealed)
    end
  end
end
