import { describe, expect, it } from "vitest";

import {
  buildDefaultMailSettings,
  parseMailSettingsValue,
  toMailSettingsFormValues,
} from "../lib/mail-settings";

describe("mail settings helpers", () => {
  it("builds safe defaults", () => {
    expect(buildDefaultMailSettings()).toEqual({
      smtp: {
        host: "",
        port: 587,
        secure: false,
        username: "",
        password: "",
      },
      sender: {
        email: "",
        name: "",
      },
      recipients: {
        contact: "",
        test: "",
      },
    });
  });

  it("parses stored values and trims strings", () => {
    const settings = parseMailSettingsValue(
      JSON.stringify({
        smtp: {
          host: " smtp.example.com ",
          port: "465",
          secure: true,
          username: " mailer ",
          password: "secret",
        },
        sender: {
          email: " hello@example.com ",
          name: " Studio Moh ",
        },
        recipients: {
          contact: " inbox@example.com ",
          test: " test@example.com ",
        },
      }),
    );

    expect(settings.smtp.host).toBe("smtp.example.com");
    expect(settings.smtp.port).toBe(465);
    expect(settings.smtp.secure).toBe(true);
    expect(settings.smtp.username).toBe("mailer");
    expect(settings.smtp.password).toBe("secret");
    expect(settings.sender.email).toBe("hello@example.com");
    expect(settings.sender.name).toBe("Studio Moh");
    expect(settings.recipients.contact).toBe("inbox@example.com");
    expect(settings.recipients.test).toBe("test@example.com");
  });

  it("falls back when json is invalid", () => {
    expect(parseMailSettingsValue("{invalid-json")).toEqual(buildDefaultMailSettings());
  });

  it("hides the saved password in form values", () => {
    const formValues = toMailSettingsFormValues({
      smtp: {
        host: "smtp.example.com",
        port: 587,
        secure: false,
        username: "mailer",
        password: "secret",
      },
      sender: {
        email: "hello@example.com",
        name: "Studio Moh",
      },
      recipients: {
        contact: "inbox@example.com",
        test: "test@example.com",
      },
    });

    expect(formValues.smtp.password).toBe("");
    expect(formValues.smtp.hasPassword).toBe(true);
  });
});
