# frozen_string_literal: true

require 'rails_helper'

module Pwb
  RSpec.describe "Editor::PageParts", type: :request do
    let(:website) { FactoryBot.create(:pwb_website, subdomain: 'editor-test') }
    let(:admin_user) { FactoryBot.create(:pwb_user, :admin, website: website) }
    let!(:page_part) do
      ActsAsTenant.with_tenant(website) do
        FactoryBot.create(:pwb_page_part,
                          page_part_key: "test_key",
                          website: website,
                          block_contents: { "en" => { "blocks" => { "title" => { "content" => "Original Title" } } } })
      end
    end

    before do
      Pwb::Current.reset
      sign_in :user, admin_user
      allow(Pwb::Current).to receive(:website).and_return(website)
      # Set host to match tenant
      host! "#{website.subdomain}.test.host"
    end

    describe "GET /editor/page_parts/:id" do
      it "returns the form partial" do
        get "/editor/page_parts/#{page_part.page_part_key}"
        expect(response).to have_http_status(:success)
      end
    end

    describe "PATCH /editor/page_parts/:id" do
      it "updates the page part content" do
        patch "/editor/page_parts/#{page_part.page_part_key}", params: {
          page_part: {
            content: {
              "en" => {
                "blocks" => {
                  "title" => { "content" => "New Title" }
                }
              }
            }
          }
        }

        expect(response).to have_http_status(:success)
        expect(page_part.reload.block_contents.dig("en", "blocks", "title", "content")).to eq("New Title")
      end
    end
  end
end
