import { beforeEach, describe, expect, it, vi } from "vitest";
import { importReportsFromJson, listReports, previewImportReports } from "./storage";
import type { ExportPayload, Report } from "./types";

const store = new Map<string, string>();

beforeEach(() => {
  store.clear();
  vi.stubGlobal("localStorage", {
    getItem: (key: string) => store.get(key) ?? null,
    setItem: (key: string, value: string) => store.set(key, value),
    removeItem: (key: string) => store.delete(key),
    clear: () => store.clear()
  });
});

const report: Report = {
  id: "rapport-1",
  report_time: "08:00:00",
  report_date: "2026-05-27",
  created_at: "2026-05-27T06:00:00.000Z",
  type: "work_report",
  work_ability: 4,
  energy_level: 3,
  mental_clarity: 4,
  symptom_burden: 2,
  effort_strain: 3,
  status: "kan_fortsette",
  physical_energy: 3,
  mental_energy: 3,
  task_types: [],
  main_limitations: [],
  helpful_accommodations: []
};

function payload(reports: Report[]): ExportPayload {
  return {
    schema_version: 2,
    export_version: 2,
    exported_at: "2026-05-27T10:00:00.000Z",
    reports
  };
}

describe("ordinær brukerimport", () => {
  it("forhåndsviser import uten å lagre data", () => {
    const summary = previewImportReports(JSON.stringify(payload([report])));

    expect(summary.reports_added).toBe(1);
    expect(listReports()).toHaveLength(0);
  });

  it("importerer nye rapporter og hopper over duplikater", () => {
    const first = importReportsFromJson(JSON.stringify(payload([report])));
    const second = importReportsFromJson(JSON.stringify(payload([report])));

    expect(first.reports_added).toBe(1);
    expect(second.reports_added).toBe(0);
    expect(second.duplicates_skipped).toBe(1);
    expect(listReports()).toHaveLength(1);
  });

  it("oppdager konflikt når samme ID har annet innhold", () => {
    importReportsFromJson(JSON.stringify(payload([report])));
    const changed = { ...report, energy_level: 1 as const };
    const summary = previewImportReports(JSON.stringify(payload([changed])));

    expect(summary.conflicts_detected).toBe(1);
    expect(summary.reports_added).toBe(0);
  });
});
