#!/usr/bin/env node

const baseUrl = process.argv[2] ?? process.env.API_BASE_URL ?? "http://127.0.0.1:8080";
const stamp = Date.now();
const email = process.env.DEV_SEED_EMAIL ?? `seed-admin-${stamp}@example.test`;

async function request(method, path, body, token) {
  const response = await fetch(`${baseUrl}${path}`, {
    method,
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  const text = await response.text();
  const data = text ? JSON.parse(text) : {};

  if (!response.ok) {
    throw new Error(`${method} ${path} failed: ${response.status} ${JSON.stringify(data)}`);
  }

  return data;
}

function assert(condition, message) {
  if (!condition) throw new Error(message);
}

async function main() {
  console.log(`creating development seed data via ${baseUrl}`);

  const bootstrap = await request("POST", "/api/v1/dev/bootstrap-local", {
    organization_name: `Seed Firma ${stamp}`,
    email,
  });
  assert(bootstrap.password, "dev bootstrap password missing");

  const login = await request("POST", "/api/v1/auth/login", {
    email,
    password: bootstrap.password,
  });
  const token = login.access_token;
  assert(token, "login token missing");

  await request("POST", "/api/v1/auth/select-organization", {
    organization_id: login.organization_id,
  }, token);

  const cashDiscountTerm = await request("POST", "/api/v1/cash-discount-terms", {
    code: `SEED-${stamp}`,
    name: "2 % Skonto, 30 Tage netto",
    discount_percent: "2.00",
    discount_days: 10,
    net_days: 30,
    valid_from: null,
    valid_until: null,
    is_default_customer_term: true,
    is_default_supplier_term: true,
    is_active: true,
  }, token);

  const customer = await request("POST", "/api/v1/customers", {
    customer_number: "",
    name: "Seed Kunde GmbH",
    status: "active",
    details: {
      street: "Kundenweg 10",
      postal_code: "60311",
      city: "Frankfurt",
      country: "Deutschland",
      email: "kunde@example.test",
      phone: "",
    },
    standard_discount_percent: "5.00",
    cash_discount_term_id: cashDiscountTerm.id,
  }, token);

  const supplier = await request("POST", "/api/v1/suppliers", {
    supplier_number: "",
    name: "Seed Lieferant GmbH",
    status: "active",
    details: {
      street: "Lieferstraße 8",
      postal_code: "10115",
      city: "Berlin",
      country: "Deutschland",
      email: "lieferant@example.test",
      phone: "",
    },
    standard_discount_percent: "0.00",
    cash_discount_term_id: cashDiscountTerm.id,
    payment_days: 30,
  }, token);

  const item = await request("POST", "/api/v1/items", {
    item_number: "",
    name: "Seed Montagestunde",
    unit: "Std",
    tax_rate: "19.00",
    default_purchase_price: "40.00",
    default_sales_price: "85.00",
    status: "active",
  }, token);

  const activity = await request("POST", "/api/v1/activities", {
    activity_number: null,
    activity_type: "task",
    title: "Seed Aktivität",
    body: "Testdaten für lokale Entwicklung.",
    status: "open",
    priority: "normal",
    due_at: null,
  }, token);

  console.log(JSON.stringify({
    email,
    password: bootstrap.password,
    organization_id: login.organization_id,
    customer_number: customer.customer_number,
    supplier_number: supplier.supplier_number,
    item_number: item.item_number,
    activity_number: activity.activity_number,
  }, null, 2));
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
