import { describe, it, expect, vi, afterEach } from "vitest";
import { render, screen, fireEvent, cleanup } from "@testing-library/react";
import { FormControllerPanel } from "@/app/editor/forms/FormControllerPanel";
import type { Block, FormBlockProps } from "@/features/editor/state/editorStore";

// FormControllerPanel 컨트롤 TDD
// - 성공/에러 메시지 인풋이 updateBlock 을 통해 FormBlockProps.successMessage / errorMessage 를 갱신하는지 검증한다.

function makeFormBlock(id: string, props: Partial<FormBlockProps> = {}): Block {
  const base: FormBlockProps = {
    kind: "contact",
    submitTarget: "internal",
    fieldIds: [],
    submitButtonId: null,
  } as any;

  return {
    id,
    type: "form",
    props: { ...base, ...props } as any,
  } as any;
}

describe("FormControllerPanel", () => {
  afterEach(() => {
    cleanup();
  });

  it("성공 메시지 인풋 변경 시 updateBlock 이 successMessage 로 호출되어야 한다", () => {
    const formBlock = makeFormBlock("form-1", {
      successMessage: "기존 성공 메시지",
    });

    const updateBlock = vi.fn();

    render(
      <FormControllerPanel
        block={formBlock}
        blocks={[formBlock]}
        selectedBlockId="form-1"
        updateBlock={updateBlock}
      />,
    );

    const input = screen.getByLabelText("성공 메시지");
    fireEvent.change(input, { target: { value: "새 성공 메시지" } });

    expect(updateBlock).toHaveBeenCalledWith(
      "form-1",
      expect.objectContaining({ successMessage: "새 성공 메시지" }),
    );
  });

  it("에러 메시지 인풋 변경 시 updateBlock 이 errorMessage 로 호출되어야 한다", () => {
    const formBlock = makeFormBlock("form-2", {
      errorMessage: "기존 에러 메시지",
    });

    const updateBlock = vi.fn();

    render(
      <FormControllerPanel
        block={formBlock}
        blocks={[formBlock]}
        selectedBlockId="form-2"
        updateBlock={updateBlock}
      />,
    );

    const input = screen.getByLabelText("에러 메시지");
    fireEvent.change(input, { target: { value: "새 에러 메시지" } });

    expect(updateBlock).toHaveBeenCalledWith(
      "form-2",
      expect.objectContaining({ errorMessage: "새 에러 메시지" }),
    );
  });
});
