# typed: false
require "rails_helper"

RSpec.describe IpAddressRole, type: :model do
  describe "validations" do
    it { is_expected.to validate_presence_of(:ip_address) }

    it "validates uniqueness of ip_address" do
      # Create a record first to test against
      IpAddressRole.create!(
        ip_address: "192.168.1.1",
        role: "user",
        active: true,
      )

      # Now test if creating another with the same IP fails
      new_role = IpAddressRole.new(ip_address: "192.168.1.1", role: "user")
      expect(new_role).not_to be_valid
      expect(new_role.errors[:ip_address]).to include("has already been taken")
    end

    context "overlapping IP ranges" do
      before do
        # Create a record with a CIDR range
        @existing_role =
          IpAddressRole.create!(
            ip_address: "192.168.0.0/16", # This covers 192.168.0.0 to 192.168.255.255
            role: "user",
            active: true,
          )
      end

      it "should not allow a new record with an overlapping IP range" do
        # This range overlaps with the existing one (192.168.1.0 to 192.168.1.255)
        new_role =
          IpAddressRole.new(
            ip_address: "192.168.1.0/24",
            role: "user",
            active: true,
          )

        expect(new_role).not_to be_valid
        expect(new_role.errors[:ip_address]).to include(
          "overlaps with an existing IP range",
        )
      end

      it "should not allow a new record with a single IP within an existing range" do
        # This single IP is within the existing range
        new_role =
          IpAddressRole.new(
            ip_address: "192.168.1.1",
            role: "user",
            active: true,
          )

        expect(new_role).not_to be_valid
        expect(new_role.errors[:ip_address]).to include(
          "overlaps with an existing IP range",
        )
      end

      it "should allow a new record with a non-overlapping IP range" do
        # This range doesn't overlap (10.0.0.0 to 10.255.255.255)
        new_role =
          IpAddressRole.new(
            ip_address: "10.0.0.0/8",
            role: "user",
            active: true,
          )

        # This should be valid since it doesn't overlap
        expect(new_role).to be_valid
      end
    end

    it { is_expected.to validate_presence_of(:role) }
  end

  describe "role" do
    it "only allows user role" do
      expect(IpAddressRole.roles.keys).to match_array(%w[user])
    end

    it "defaults to user role" do
      ip_role = IpAddressRole.new
      expect(ip_role.role).to eq("user")
    end
  end
end
