// @ts-nocheck
/**
 * Drizzle 声明式 schema 与项目 src/tsconfig.json 的 `isolatedDeclarations` 风格不兼容
 *（sqliteTable 返回类型极深，无法手写显式标注）。因此 schema 文件由独立的
 * `src/server/storage/drizzle/schema/tsconfig.json` 管理（isolatedDeclarations: false），
 * 并在文件头关闭对主工程 isolatedDeclarations 的检查。运行时类型安全仍由 dialect/store 保证。
 */
import { sql } from "drizzle-orm";
import { check, index, integer, primaryKey, sqliteTable, text } from "drizzle-orm/sqlite-core";
import { IDEMPOTENCY_STATE_CHECK, IDEMPOTENCY_STATE_RESPONSE_CHECK, RUNTIME_INDEX_NAMES } from "./columns.ts";

/**
 * Runtime storage schema for the SQLite dialect (self-hosted Node backend).
 *
 * Column wire format matches the legacy migrations/0001~0006.sql exactly so that
 * existing connect.sqlite files are adopted without re-running migrations:
 * - all `value` columns are text (JSON.stringify'd JSON or AES ciphertext);
 * - id/uuid primary keys are text (crypto.randomUUID() generated in JS);
 * - runs.ok is integer-with-boolean-mode (legacy on-disk format is 0/1).
 */

export const connections: any = sqliteTable(
  "connections",
  {
    id: text("id").notNull().unique(),
    service: text("service").notNull(),
    connectionName: text("connection_name").notNull(),
    value: text("value").notNull(),
    updatedAt: text("updated_at").notNull(),
  },
  (table) => [primaryKey({ columns: [table.service, table.connectionName] })],
);

export const oauthClientConfigs: any = sqliteTable("oauth_client_configs", {
  service: text("service").primaryKey(),
  value: text("value").notNull(),
  updatedAt: text("updated_at").notNull(),
});

export const oauthStates: any = sqliteTable("oauth_states", {
  state: text("state").primaryKey(),
  value: text("value").notNull(),
  createdAt: text("created_at").notNull(),
});

export const runtimeTokens: any = sqliteTable("runtime_tokens", {
  id: text("id").primaryKey(),
  name: text("name").notNull(),
  tokenHash: text("token_hash").notNull().unique(),
  createdAt: text("created_at").notNull(),
  lastUsedAt: text("last_used_at"),
  revokedAt: text("revoked_at"),
});

export const runs: any = sqliteTable(
  "runs",
  {
    id: text("id").primaryKey(),
    actionId: text("action_id").notNull(),
    startedAt: text("started_at").notNull(),
    completedAt: text("completed_at").notNull(),
    ok: integer("ok", { mode: "boolean" }).notNull(),
    value: text("value").notNull(),
    service: text("service"),
    caller: text("caller"),
  },
  (table) => [
    index(RUNTIME_INDEX_NAMES.runsServiceStartedAtId).on(
      table.service,
      sql`${table.startedAt} desc`,
      sql`${table.id} desc`,
    ),
    index(RUNTIME_INDEX_NAMES.runsActionIdStartedAtId).on(
      table.actionId,
      sql`${table.startedAt} desc`,
      sql`${table.id} desc`,
    ),
    index(RUNTIME_INDEX_NAMES.runsCallerStartedAtId).on(
      table.caller,
      sql`${table.startedAt} desc`,
      sql`${table.id} desc`,
    ),
    index(RUNTIME_INDEX_NAMES.runsOkStartedAtId).on(table.ok, sql`${table.startedAt} desc`, sql`${table.id} desc`),
    index(RUNTIME_INDEX_NAMES.runsStartedAtId).on(sql`${table.startedAt} desc`, sql`${table.id} desc`),
  ],
);

export const idempotencyRecords: any = sqliteTable(
  "idempotency_records",
  {
    keyHash: text("key_hash").primaryKey(),
    claimId: text("claim_id").notNull(),
    requestHash: text("request_hash").notNull(),
    state: text("state").notNull(),
    responseValue: text("response_value"),
    createdAt: text("created_at").notNull(),
    expiresAt: text("expires_at").notNull(),
  },
  (table) => [
    index(RUNTIME_INDEX_NAMES.idempotencyRecordsExpiresAt).on(table.expiresAt),
    check("idempotency_state_check", sql.raw(IDEMPOTENCY_STATE_CHECK)),
    check("idempotency_state_response_check", sql.raw(IDEMPOTENCY_STATE_RESPONSE_CHECK)),
  ],
);

export const sqliteRuntimeSchema: any = {
  connections,
  oauthClientConfigs,
  oauthStates,
  runtimeTokens,
  runs,
  idempotencyRecords,
};

export type SqliteRuntimeSchema = any;
