import { createRequire } from 'module';
import * as Context2 from 'effect/Context';
import * as Effect3 from 'effect/Effect';
import * as Exit2 from 'effect/Exit';
import * as Mailbox2 from 'effect/Mailbox';
import * as Scope2 from 'effect/Scope';
import * as Stream2 from 'effect/Stream';
import * as Clock from 'effect/Clock';
import * as FiberRef from 'effect/FiberRef';
import * as Option from 'effect/Option';
import * as Tracer from 'effect/Tracer';
import * as Effectable from 'effect/Effectable';
import { identity } from 'effect/Function';
import { globalValue } from 'effect/GlobalValue';
import { Effect } from 'effect';

createRequire(import.meta.url);
var __defProp = Object.defineProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};

// ../../node_modules/.pnpm/@effect+sql@0.40.1_@effect+experimental@0.51.1_@effect+platform@0.87.1_effect@3.16.10___655b716b8b22369ab6d8fc17ca4d3aef/node_modules/@effect/sql/dist/esm/SqlClient.js
var SqlClient_exports = {};
__export(SqlClient_exports, {
  SafeIntegers: () => SafeIntegers,
  SqlClient: () => SqlClient,
  TransactionConnection: () => TransactionConnection2,
  TypeId: () => TypeId2,
  make: () => make6,
  makeWithTransaction: () => makeWithTransaction2
});
var Reactivity = class extends (/* @__PURE__ */ Context2.Tag("@effect/experimental/Reactivity")()) {
};

// ../../node_modules/.pnpm/@opentelemetry+semantic-conventions@1.34.0/node_modules/@opentelemetry/semantic-conventions/build/esm/trace/SemanticAttributes.js
var TMP_DB_STATEMENT = "db.statement";
var TMP_DB_OPERATION = "db.operation";
var SEMATTRS_DB_STATEMENT = TMP_DB_STATEMENT;
var SEMATTRS_DB_OPERATION = TMP_DB_OPERATION;
var FragmentId = /* @__PURE__ */ Symbol.for("@effect/sql/Fragment");
var isFragment = (u) => typeof u === "object" && u !== null && FragmentId in u;
var currentTransformer = /* @__PURE__ */ globalValue("@effect/sql/Statement/currentTransformer", () => FiberRef.unsafeMake(Option.none()));
var withStatement = (self, span, f) => Effect3.withFiberRuntime((fiber) => {
  const transform = fiber.getFiberRef(currentTransformer);
  if (transform._tag === "None") {
    return f(self);
  }
  return Effect3.flatMap(transform.value(self, make2(self.acquirer, self.compiler, self.spanAttributes, self.transformRows), fiber.getFiberRefs(), span), f);
});
var StatementPrimitive = class extends Effectable.Class {
  segments;
  acquirer;
  compiler;
  spanAttributes;
  transformRows;
  get [FragmentId]() {
    return identity;
  }
  constructor(segments, acquirer, compiler, spanAttributes, transformRows) {
    super();
    this.segments = segments;
    this.acquirer = acquirer;
    this.compiler = compiler;
    this.spanAttributes = spanAttributes;
    this.transformRows = transformRows;
  }
  withConnection(operation, f, withoutTransform = false) {
    return Effect3.useSpan("sql.execute", {
      kind: "client",
      captureStackTrace: false
    }, (span) => withStatement(this, span, (statement2) => {
      const [sql, params] = statement2.compile(withoutTransform);
      for (const [key, value] of this.spanAttributes) {
        span.attribute(key, value);
      }
      span.attribute(SEMATTRS_DB_OPERATION, operation);
      span.attribute(SEMATTRS_DB_STATEMENT, sql);
      return Effect3.scoped(Effect3.flatMap(this.acquirer, (_) => f(_, sql, params)));
    }));
  }
  get withoutTransform() {
    return this.withConnection("executeWithoutTransform", (connection, sql, params) => connection.execute(sql, params, void 0), true);
  }
  get raw() {
    return this.withConnection("executeRaw", (connection, sql, params) => connection.executeRaw(sql, params), true);
  }
  get stream() {
    return Stream2.unwrapScoped(Effect3.flatMap(Effect3.makeSpanScoped("sql.execute", {
      kind: "client",
      captureStackTrace: false
    }), (span) => withStatement(this, span, (statement2) => {
      const [sql, params] = statement2.compile();
      for (const [key, value] of this.spanAttributes) {
        span.attribute(key, value);
      }
      span.attribute(SEMATTRS_DB_OPERATION, "executeStream");
      span.attribute(SEMATTRS_DB_STATEMENT, sql);
      return Effect3.map(this.acquirer, (_) => _.executeStream(sql, params, this.transformRows));
    })));
  }
  get values() {
    return this.withConnection("executeValues", (connection, sql, params) => connection.executeValues(sql, params));
  }
  get unprepared() {
    return this.withConnection("executeUnprepared", (connection, sql, params) => connection.executeUnprepared(sql, params, this.transformRows));
  }
  compile(withoutTransform) {
    return this.compiler.compile(this, withoutTransform ?? false);
  }
  commit() {
    return this.withConnection("execute", (connection, sql, params) => connection.execute(sql, params, this.transformRows));
  }
  toJSON() {
    const [sql, params] = this.compile();
    return {
      _id: "@effect/sql/Statement",
      segments: this.segments,
      sql,
      params
    };
  }
};
var FragmentImpl = class {
  segments;
  get [FragmentId]() {
    return identity;
  }
  constructor(segments) {
    this.segments = segments;
  }
};
var LiteralImpl = class {
  value;
  params;
  _tag = "Literal";
  constructor(value, params) {
    this.value = value;
    this.params = params;
  }
};
var IdentifierImpl = class {
  value;
  _tag = "Identifier";
  constructor(value) {
    this.value = value;
  }
};
var ParameterImpl = class {
  value;
  _tag = "Parameter";
  constructor(value) {
    this.value = value;
  }
};
var ArrayHelperImpl = class {
  value;
  _tag = "ArrayHelper";
  constructor(value) {
    this.value = value;
  }
};
function identifierWrap(sql) {
  return typeof sql === "string" ? sql : FragmentId in sql ? sql : new FragmentImpl([sql]);
}
var RecordInsertHelperImpl = class _RecordInsertHelperImpl {
  value;
  returningIdentifier;
  _tag = "RecordInsertHelper";
  constructor(value, returningIdentifier) {
    this.value = value;
    this.returningIdentifier = returningIdentifier;
  }
  returning(sql) {
    return new _RecordInsertHelperImpl(this.value, identifierWrap(sql));
  }
};
var RecordUpdateHelperImpl = class _RecordUpdateHelperImpl {
  value;
  alias;
  returningIdentifier;
  _tag = "RecordUpdateHelper";
  constructor(value, alias, returningIdentifier) {
    this.value = value;
    this.alias = alias;
    this.returningIdentifier = returningIdentifier;
  }
  returning(sql) {
    return new _RecordUpdateHelperImpl(this.value, this.alias, identifierWrap(sql));
  }
};
var RecordUpdateHelperSingleImpl = class _RecordUpdateHelperSingleImpl {
  value;
  omit;
  returningIdentifier;
  _tag = "RecordUpdateHelperSingle";
  constructor(value, omit, returningIdentifier) {
    this.value = value;
    this.omit = omit;
    this.returningIdentifier = returningIdentifier;
  }
  returning(sql) {
    return new _RecordUpdateHelperSingleImpl(this.value, this.omit, identifierWrap(sql));
  }
};
var isHelper = (u) => u instanceof ArrayHelperImpl || u instanceof RecordInsertHelperImpl || u instanceof RecordUpdateHelperImpl || u instanceof RecordUpdateHelperSingleImpl || u instanceof IdentifierImpl;
var constructorCache = /* @__PURE__ */ globalValue("@effect/sql/Statement/constructorCache", () => ({
  transforms: /* @__PURE__ */ new WeakMap(),
  noTransforms: /* @__PURE__ */ new WeakMap()
}));
var make2 = (acquirer, compiler, spanAttributes, transformRows) => {
  const cache = transformRows === void 0 ? constructorCache.noTransforms : constructorCache.transforms;
  if (cache.has(acquirer)) {
    return cache.get(acquirer);
  }
  const self = Object.assign(function sql(strings, ...args) {
    if (Array.isArray(strings) && "raw" in strings) {
      return statement(acquirer, compiler, strings, args, spanAttributes, transformRows);
    } else if (typeof strings === "string") {
      return new IdentifierImpl(strings);
    }
    throw "absurd";
  }, {
    unsafe(sql, params) {
      return new StatementPrimitive([new LiteralImpl(sql, params)], acquirer, compiler, spanAttributes, transformRows);
    },
    literal(sql) {
      return new FragmentImpl([new LiteralImpl(sql)]);
    },
    in: in_,
    insert(value) {
      return new RecordInsertHelperImpl(Array.isArray(value) ? value : [value], void 0);
    },
    update(value, omit) {
      return new RecordUpdateHelperSingleImpl(value, omit ?? [], void 0);
    },
    updateValues(value, alias) {
      return new RecordUpdateHelperImpl(value, alias, void 0);
    },
    and,
    or,
    csv,
    join,
    onDialect(options) {
      return options[compiler.dialect]();
    },
    onDialectOrElse(options) {
      return options[compiler.dialect] !== void 0 ? options[compiler.dialect]() : options.orElse();
    }
  });
  cache.set(acquirer, self);
  return self;
};
var statement = (acquirer, compiler, strings, args, spanAttributes, transformRows) => {
  const segments = strings[0].length > 0 ? [new LiteralImpl(strings[0])] : [];
  for (let i = 0; i < args.length; i++) {
    const arg = args[i];
    if (isFragment(arg)) {
      for (const segment of arg.segments) {
        segments.push(segment);
      }
    } else if (isHelper(arg)) {
      segments.push(arg);
    } else {
      segments.push(new ParameterImpl(arg));
    }
    if (strings[i + 1].length > 0) {
      segments.push(new LiteralImpl(strings[i + 1]));
    }
  }
  return new StatementPrimitive(segments, acquirer, compiler, spanAttributes, transformRows);
};
var unsafeFragment = (sql, params) => new FragmentImpl([new LiteralImpl(sql, params)]);
function convertLiteralOrFragment(clause) {
  if (typeof clause === "string") {
    return [new LiteralImpl(clause)];
  }
  return clause.segments;
}
function in_() {
  if (arguments.length === 1) {
    return new ArrayHelperImpl(arguments[0]);
  }
  const column = arguments[0];
  const values = arguments[1];
  return values.length === 0 ? unsafeFragment("1=0") : new FragmentImpl([new IdentifierImpl(column), new LiteralImpl(" IN "), new ArrayHelperImpl(values)]);
}
function join(literal, addParens = true, fallback = "") {
  const literalStatement = new LiteralImpl(literal);
  return (clauses) => {
    if (clauses.length === 0) {
      return unsafeFragment(fallback);
    } else if (clauses.length === 1) {
      return new FragmentImpl(convertLiteralOrFragment(clauses[0]));
    }
    const segments = [];
    if (addParens) {
      segments.push(new LiteralImpl("("));
    }
    segments.push.apply(segments, convertLiteralOrFragment(clauses[0]));
    for (let i = 1; i < clauses.length; i++) {
      segments.push(literalStatement);
      segments.push.apply(segments, convertLiteralOrFragment(clauses[i]));
    }
    if (addParens) {
      segments.push(new LiteralImpl(")"));
    }
    return new FragmentImpl(segments);
  };
}
var and = /* @__PURE__ */ join(" AND ", true, "1=1");
var or = /* @__PURE__ */ join(" OR ", true, "1=1");
var csvRaw = /* @__PURE__ */ join(", ", false);
var csv = (...args) => {
  if (args[args.length - 1].length === 0) {
    return unsafeFragment("");
  }
  if (args.length === 1) {
    return csvRaw(args[0]);
  }
  return new FragmentImpl([new LiteralImpl(`${args[0]} `), ...csvRaw(args[1]).segments]);
};

// ../../node_modules/.pnpm/@effect+sql@0.40.1_@effect+experimental@0.51.1_@effect+platform@0.87.1_effect@3.16.10___655b716b8b22369ab6d8fc17ca4d3aef/node_modules/@effect/sql/dist/esm/Statement.js
var make3 = make2;

// ../../node_modules/.pnpm/@effect+sql@0.40.1_@effect+experimental@0.51.1_@effect+platform@0.87.1_effect@3.16.10___655b716b8b22369ab6d8fc17ca4d3aef/node_modules/@effect/sql/dist/esm/internal/client.js
var TypeId = /* @__PURE__ */ Symbol.for("@effect/sql/SqlClient");
var clientTag = /* @__PURE__ */ Context2.GenericTag("@effect/sql/SqlClient");
var TransactionConnection = /* @__PURE__ */ Context2.GenericTag("@effect/sql/SqlClient/TransactionConnection");
function make5({
  acquirer,
  beginTransaction = "BEGIN",
  commit = "COMMIT",
  compiler,
  reactiveMailbox,
  rollback = "ROLLBACK",
  rollbackSavepoint = (id) => `ROLLBACK TO SAVEPOINT ${id}`,
  savepoint = (id) => `SAVEPOINT ${id}`,
  spanAttributes,
  transactionAcquirer,
  transformRows
}) {
  return Effect3.gen(function* () {
    const getConnection = Effect3.flatMap(Effect3.serviceOption(TransactionConnection), Option.match({
      onNone: () => acquirer,
      onSome: ([conn]) => Effect3.succeed(conn)
    }));
    transactionAcquirer = transactionAcquirer ?? acquirer;
    const withTransaction = makeWithTransaction({
      transactionTag: TransactionConnection,
      spanAttributes,
      acquireConnection: Effect3.flatMap(Scope2.make(), (scope2) => Effect3.map(Scope2.extend(transactionAcquirer, scope2), (conn) => [scope2, conn])),
      begin: (conn) => conn.executeUnprepared(beginTransaction, [], void 0),
      savepoint: (conn, id) => conn.executeUnprepared(savepoint(`effect_sql_${id}`), [], void 0),
      commit: (conn) => conn.executeUnprepared(commit, [], void 0),
      rollback: (conn) => conn.executeUnprepared(rollback, [], void 0),
      rollbackSavepoint: (conn, id) => conn.executeUnprepared(rollbackSavepoint(`effect_sql_${id}`), [], void 0)
    });
    const reactivity = yield* Reactivity;
    const client = Object.assign(make3(getConnection, compiler, spanAttributes, transformRows), {
      [TypeId]: TypeId,
      safe: void 0,
      withTransaction,
      reserve: transactionAcquirer,
      withoutTransforms() {
        if (transformRows === void 0) {
          return this;
        }
        const statement2 = make3(getConnection, compiler.withoutTransform, spanAttributes, void 0);
        const client2 = Object.assign(statement2, {
          ...this,
          ...statement2
        });
        client2.safe = client2;
        client2.withoutTransforms = () => client2;
        return client2;
      },
      reactive: reactiveMailbox ? (keys, effect) => reactiveMailbox(keys, effect).pipe(Effect3.map(Mailbox2.toStream), Stream2.unwrapScoped) : reactivity.stream,
      reactiveMailbox: reactiveMailbox ?? reactivity.query
    });
    client.safe = client;
    return client;
  });
}
var makeWithTransaction = (options) => (effect) => Effect3.uninterruptibleMask((restore) => Effect3.useSpan("sql.transaction", {
  kind: "client",
  captureStackTrace: false
}, (span) => Effect3.withFiberRuntime((fiber) => {
  for (const [key, value] of options.spanAttributes) {
    span.attribute(key, value);
  }
  const context = fiber.currentContext;
  const clock = Context2.get(fiber.currentDefaultServices, Clock.Clock);
  const connOption = Context2.getOption(context, options.transactionTag);
  const conn = connOption._tag === "Some" ? Effect3.succeed([void 0, connOption.value[0]]) : options.acquireConnection;
  const id = connOption._tag === "Some" ? connOption.value[1] + 1 : 0;
  return Effect3.flatMap(conn, ([scope2, conn2]) => (id === 0 ? options.begin(conn2) : options.savepoint(conn2, id)).pipe(Effect3.zipRight(Effect3.locally(restore(effect), FiberRef.currentContext, Context2.add(context, options.transactionTag, [conn2, id]).pipe(Context2.add(Tracer.ParentSpan, span)))), Effect3.exit, Effect3.flatMap((exit2) => {
    let effect2;
    if (Exit2.isSuccess(exit2)) {
      if (id === 0) {
        span.event("db.transaction.commit", clock.unsafeCurrentTimeNanos());
        effect2 = Effect3.orDie(options.commit(conn2));
      } else {
        span.event("db.transaction.savepoint", clock.unsafeCurrentTimeNanos());
        effect2 = Effect3.void;
      }
    } else {
      span.event("db.transaction.rollback", clock.unsafeCurrentTimeNanos());
      effect2 = Effect3.orDie(id > 0 ? options.rollbackSavepoint(conn2, id) : options.rollback(conn2));
    }
    const withScope = scope2 !== void 0 ? Effect3.ensuring(effect2, Scope2.close(scope2, exit2)) : effect2;
    return Effect3.zipRight(withScope, exit2);
  })));
})));

// ../../node_modules/.pnpm/@effect+sql@0.40.1_@effect+experimental@0.51.1_@effect+platform@0.87.1_effect@3.16.10___655b716b8b22369ab6d8fc17ca4d3aef/node_modules/@effect/sql/dist/esm/SqlClient.js
var TypeId2 = TypeId;
var SqlClient = clientTag;
var make6 = make5;
var makeWithTransaction2 = makeWithTransaction;
var TransactionConnection2 = TransactionConnection;
var SafeIntegers = class extends (/* @__PURE__ */ Context2.Reference()("@effect/sql/SqlClient/SafeIntegers", {
  defaultValue: () => false
})) {
};
var create_table_app_events_default = Effect.flatMap(
  SqlClient_exports.SqlClient,
  (sql) => sql`
    CREATE TABLE IF NOT EXISTS app_event (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      app_id INTEGER NOT NULL,
      event_type TEXT NOT NULL,
      metadata TEXT NOT NULL,
      created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,

      FOREIGN KEY (app_id) REFERENCES app(id) ON DELETE CASCADE
    )
  `
);

export { create_table_app_events_default as default };
