import { describe, expect, it } from "vitest";
import {
  createBucketInput,
  isForbidden,
  isMissingBucket,
  isMissingObject,
  optionalEnv,
  s3CorsOrigins,
  s3CustomEndpoint,
} from "./s3-env";

describe("s3 env", () => {
  it("treats blank values as unset so leftover MinIO keys do not force a custom endpoint", () => {
    expect(optionalEnv("S3_ENDPOINT", { S3_ENDPOINT: "  " })).toBeUndefined();
    expect(s3CustomEndpoint({ S3_ENDPOINT: "" })).toBeUndefined();
    expect(s3CustomEndpoint({ S3_ENDPOINT: "https://s3.us-west-2.amazonaws.com" })).toBe(
      "https://s3.us-west-2.amazonaws.com",
    );
  });

  it("omits LocationConstraint for us-east-1 and for S3-compatible endpoints", () => {
    expect(createBucketInput("files", "us-east-1")).toEqual({ Bucket: "files" });
    expect(createBucketInput("files", "us-west-2", "http://localhost:9000")).toEqual({ Bucket: "files" });
  });

  it("sets LocationConstraint when creating an Amazon S3 bucket outside us-east-1", () => {
    expect(createBucketInput("files", "us-west-2")).toEqual({
      Bucket: "files",
      CreateBucketConfiguration: { LocationConstraint: "us-west-2" },
    });
  });

  it("parses CORS origins", () => {
    expect(s3CorsOrigins({ S3_CORS_ORIGINS: "https://app.example, http://localhost:3000" })).toEqual([
      "https://app.example",
      "http://localhost:3000",
    ]);
  });
});

describe("s3 error classification", () => {
  it("treats HeadBucket 403 UnknownError as forbidden, not missing", () => {
    const forbidden = { name: "Unknown", message: "UnknownError", $metadata: { httpStatusCode: 403 } };
    expect(isForbidden(forbidden)).toBe(true);
    expect(isMissingBucket(forbidden)).toBe(false);
    expect(isMissingObject({ name: "NotFound", $metadata: { httpStatusCode: 404 } })).toBe(true);
  });
});
