require "rails_helper"

RSpec.describe Teams::StaffAssignment do
  let!(:owner) { User.create!(name: "Owner", email: "owner@test.com", password: "password123", role: "coach") }
  let!(:club) { Club.create!(name: "Club", sport: "volleyball", primary_color: "#e53935", secondary_color: "#ffffff") }
  let!(:team) { club.teams.create!(name: "Team", sport: "volleyball") }
  let!(:other) { User.create!(name: "Other", email: "other@test.com", password: "password123", role: "coach") }

  before do
    ClubMembership.create!(user: owner, club: club, role: "owner")
    load Rails.root.join("db/seeds/plans.rb")
    Billing::AssignPlan.call(club: club, plan_slug: "free")
  end

  it "assigns transmission to owner" do
    membership = UserTeam.create!(user: owner, team: team, role: "member")
    described_class.call(team: team, user: owner, membership: membership)
    expect(membership.reload.staff_kind).to eq("transmission")
    expect(team.entitlements.staff_count_for("transmission")).to eq(1)
  end

  it "rejects duplicate email for transmission" do
    UserTeam.create!(user: other, team: team, role: "member", staff_kind: "transmission")
    expect {
      Teams::StaffEmailValidator.assert_available!(team: team, email: other.email)
    }.to raise_error(Teams::StaffAssignmentError, /già assegnata/)
  end
end
