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
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
import {
  createClient,
  QueryResult as VercelQueryResult,
} from "@vercel/postgres";
import { Pool, PoolClient } from "pg";

const isVercel = process.env.VERCEL === "1";

let vercelPool: {
  client: ReturnType<typeof createClient>;
  isConnected: boolean;
} | null = null;
let pgPool: Pool | null = null;

async function getVercelClient() {
  if (!vercelPool) {
    vercelPool = {
      client: createClient(),
      isConnected: false,
    };
  }

  if (!vercelPool.isConnected) {
    try {
      await vercelPool.client.connect();
      vercelPool.isConnected = true;
    } catch (error) {
      console.error("Vercel DB connection error:", error);
      throw error;
    }
  }

  return vercelPool.client;
}

function getClient() {
  if (isVercel) {
    return getVercelClient();
  } else {
    if (!pgPool) {
      const config = {
        host: process.env.POSTGRES_HOST || "db",
        user: process.env.POSTGRES_USER || "postgres",
        password: process.env.POSTGRES_PASSWORD,
        database: process.env.POSTGRES_DATABASE || "openwebui_monitor",
        port: parseInt(process.env.POSTGRES_PORT || "5432"),
        max: 20,
        idleTimeoutMillis: 30000,
        connectionTimeoutMillis: 30000,
        statement_timeout: 30000,
      };

      if (process.env.POSTGRES_URL) {
        pgPool = new Pool({
          connectionString: process.env.POSTGRES_URL,
          ssl: {
            rejectUnauthorized: false,
          },
          max: 20,
          idleTimeoutMillis: 30000,
          connectionTimeoutMillis: 30000,
          statement_timeout: 30000,
        });
      } else {
        pgPool = new Pool(config);
      }

      pgPool.on("error", (err) => {
        console.error("Unexpected error on idle client", err);
        process.exit(-1);
      });
    }
    return pgPool;
  }
}

type CommonQueryResult<T = any> = {
  rows: T[];
  rowCount: number;
};

export async function query<T = any>(
  text: string,
  params?: any[]
): Promise<CommonQueryResult<T>> {
  const client = await getClient();
  const startTime = Date.now();

  if (isVercel) {
    try {
      const result = await (client as ReturnType<typeof createClient>).query({
        text,
        values: params || [],
      });
      return {
        rows: result.rows,
        rowCount: result.rowCount || 0,
      };
    } catch (error) {
      console.error("[DB Query Error]", error);
      if (vercelPool) {
        vercelPool.isConnected = false;
      }
      throw error;
    }
  } else {
    let pgClient;
    try {
      pgClient = await (client as Pool).connect();
      const result = await pgClient.query(text, params);
      return {
        rows: result.rows,
        rowCount: result.rowCount || 0,
      };
    } catch (error) {
      console.error("[DB Query Error]", error);
      console.error(`Query text: ${text}`);
      console.error(`Query params:`, params);
      throw error;
    } finally {
      if (pgClient) {
        pgClient.release();
      }
    }
  }
}

if (typeof window === "undefined") {
  process.on("SIGTERM", async () => {
    console.log("SIGTERM received, closing database connections");
    if (pgPool) {
      await pgPool.end();
    }
    if (vercelPool?.client) {
      await vercelPool.client.end();
      vercelPool.isConnected = false;
    }
  });
}

export { getClient };

export async function ensureTablesExist() {
  try {
    const usersTableExists = await query(`
      SELECT EXISTS (
        SELECT FROM information_schema.tables 
        WHERE table_name = 'users'
      );
    `);

    if (!usersTableExists.rows[0].exists) {
      await query(`
        CREATE TABLE IF NOT EXISTS users (
          id TEXT PRIMARY KEY,
          email TEXT NOT NULL,
          name TEXT NOT NULL,
          role TEXT NOT NULL DEFAULT 'user',
          balance DECIMAL(16, 6) NOT NULL DEFAULT 0,
          created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
          deleted BOOLEAN DEFAULT FALSE
        );
      `);
    } else {
      try {
        await query(`
          DO $$ 
          BEGIN 
            BEGIN
              ALTER TABLE users 
              ADD COLUMN deleted BOOLEAN DEFAULT FALSE;
            EXCEPTION 
              WHEN duplicate_column THEN NULL;
            END;
          END $$;
        `);
      } catch (error) {
        console.error("Error adding deleted column to users table:", error);
      }
    }

    const modelPricesTableExists = await query(`
      SELECT EXISTS (
        SELECT FROM information_schema.tables 
        WHERE table_name = 'model_prices'
      );
    `);

    const defaultInputPrice = parseFloat(
      process.env.DEFAULT_MODEL_INPUT_PRICE || "60"
    );
    const defaultOutputPrice = parseFloat(
      process.env.DEFAULT_MODEL_OUTPUT_PRICE || "60"
    );
    const defaultPerMsgPrice = parseFloat(
      process.env.DEFAULT_MODEL_PER_MSG_PRICE || "-1"
    );

    if (!modelPricesTableExists.rows[0].exists) {
      await query(`
        CREATE TABLE IF NOT EXISTS model_prices (
          id TEXT PRIMARY KEY,
          name TEXT NOT NULL,
          base_model_id TEXT,
          input_price NUMERIC(10, 6) DEFAULT ${defaultInputPrice},
          output_price NUMERIC(10, 6) DEFAULT ${defaultOutputPrice},
          per_msg_price NUMERIC(10, 6) DEFAULT ${defaultPerMsgPrice},
          updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
        );
      `);
    } else {
      try {
        await query(`
          DO $$ 
          BEGIN 
            BEGIN
              ALTER TABLE model_prices 
              ADD COLUMN per_msg_price NUMERIC(10, 6) DEFAULT ${defaultPerMsgPrice};
            EXCEPTION 
              WHEN duplicate_column THEN NULL;
            END;
          END $$;
        `);
      } catch (error) {
        console.error("Error adding per_msg_price column:", error);
      }

      try {
        await query(`
          DO $$ 
          BEGIN 
            BEGIN
              ALTER TABLE model_prices 
              ADD COLUMN base_model_id TEXT;
            EXCEPTION 
              WHEN duplicate_column THEN NULL;
            END;
          END $$;
        `);
      } catch (error) {
        console.error("Error adding base_model_id column:", error);
      }
    }

    const userUsageRecordsTableExists = await query(`
      SELECT EXISTS (
        SELECT FROM information_schema.tables 
        WHERE table_name = 'user_usage_records'
      );
    `);

    if (!userUsageRecordsTableExists.rows[0].exists) {
      await query(`
        CREATE TABLE IF NOT EXISTS user_usage_records (
          id SERIAL PRIMARY KEY,
          user_id TEXT NOT NULL,
          nickname VARCHAR(255) NOT NULL,
          use_time TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
          model_name VARCHAR(255) NOT NULL,
          input_tokens INTEGER NOT NULL,
          output_tokens INTEGER NOT NULL,
          cost DECIMAL(10, 4) NOT NULL,
          balance_after DECIMAL(10, 4) NOT NULL,
          FOREIGN KEY (user_id) REFERENCES users(id)
        );
      `);
    }

    console.log("Database tables initialized successfully");
  } catch (error) {
    console.error("Failed to initialize database tables:", error);
    throw error;
  }
}

export async function initDatabase() {
  try {
    await ensureTablesExist();
    console.log("Database initialized successfully");
  } catch (error) {
    console.error("Failed to initialize database:", error);
    throw error;
  }
}

export interface ModelPrice {
  id: string;
  name: string;
  input_price: number;
  output_price: number;
  per_msg_price: number;
  updated_at: Date;
}

export interface UserUsageRecord {
  id: number;
  userId: number;
  nickname: string;
  useTime: Date;
  modelName: string;
  inputTokens: number;
  outputTokens: number;
  cost: number;
  balanceAfter: number;
}

export async function getOrCreateModelPrices(
  models: Array<{ id: string; name: string; base_model_id?: string }>
): Promise<ModelPrice[]> {
  try {
    const defaultInputPrice = parseFloat(
      process.env.DEFAULT_MODEL_INPUT_PRICE || "60"
    );
    const defaultOutputPrice = parseFloat(
      process.env.DEFAULT_MODEL_OUTPUT_PRICE || "60"
    );
    const defaultPerMsgPrice = parseFloat(
      process.env.DEFAULT_MODEL_PER_MSG_PRICE || "-1"
    );

    const modelIds = models.map((m) => m.id);
    const baseModelIds = models.map((m) => m.base_model_id).filter((id) => id);

    const existingModelsResult = await query(
      `SELECT * FROM model_prices WHERE id = ANY($1::text[])`,
      [modelIds]
    );

    const baseModelsResult = await query(
      `SELECT * FROM model_prices WHERE id = ANY($1::text[])`,
      [baseModelIds]
    );

    const existingModels = new Map(
      existingModelsResult.rows.map((row) => [row.id, row])
    );
    const baseModels = new Map(
      baseModelsResult.rows.map((row) => [row.id, row])
    );

    const modelsToUpdate = models.filter((m) => existingModels.has(m.id));
    const missingModels = models.filter((m) => !existingModels.has(m.id));

    if (modelsToUpdate.length > 0) {
      for (const model of modelsToUpdate) {
        await query(`UPDATE model_prices SET name = $2 WHERE id = $1`, [
          model.id,
          model.name,
        ]);
      }
    }

    if (missingModels.length > 0) {
      for (const model of missingModels) {
        const baseModel = model.base_model_id
          ? baseModels.get(model.base_model_id)
          : null;

        await query(
          `INSERT INTO model_prices (id, name, input_price, output_price, per_msg_price)
           VALUES ($1, $2, $3, $4, $5)
           RETURNING *`,
          [
            model.id,
            model.name,
            baseModel?.input_price ?? defaultInputPrice,
            baseModel?.output_price ?? defaultOutputPrice,
            baseModel?.per_msg_price ?? defaultPerMsgPrice,
          ]
        );
      }
    }

    const updatedModelsResult = await query(
      `SELECT * FROM model_prices WHERE id = ANY($1::text[])`,
      [modelIds]
    );

    return updatedModelsResult.rows.map((row) => ({
      id: row.id,
      name: row.name,
      input_price: Number(row.input_price),
      output_price: Number(row.output_price),
      per_msg_price: Number(row.per_msg_price),
      updated_at: row.updated_at,
    }));
  } catch (error) {
    console.error("Error in getOrCreateModelPrices:", error);
    throw error;
  }
}

export async function updateModelPrice(
  id: string,
  input_price: number,
  output_price: number,
  per_msg_price: number
): Promise<ModelPrice | null> {
  try {
    const result = await query(
      `UPDATE model_prices 
       SET 
         input_price = CAST($2 AS NUMERIC(10,6)),
         output_price = CAST($3 AS NUMERIC(10,6)),
         per_msg_price = CAST($4 AS NUMERIC(10,6)),
         updated_at = CURRENT_TIMESTAMP
       WHERE id = $1
       RETURNING *`,
      [id, input_price, output_price, per_msg_price]
    );

    if (result.rows[0]) {
      return {
        id: result.rows[0].id,
        name: result.rows[0].model_name,
        input_price: Number(result.rows[0].input_price),
        output_price: Number(result.rows[0].output_price),
        per_msg_price: Number(result.rows[0].per_msg_price),
        updated_at: result.rows[0].updated_at,
      };
    }
    return null;
  } catch (error) {
    console.error("Error updating model price:", error);
    throw error;
  }
}

export async function updateUserBalance(userId: string, balance: number) {
  try {
    const result = await query(
      `UPDATE users
       SET balance = $2
       WHERE id = $1
       RETURNING id, email, balance`,
      [userId, balance]
    );

    return result.rows[0];
  } catch (error) {
    console.error("Error in updateUserBalance:", error);
    throw error;
  }
}

export const pool = {
  connect: async () => {
    if (isVercel) {
      return {
        query: async (text: string, params?: any[]) => {
          const client = await getVercelClient();
          const result = await client.query({
            text,
            values: params || [],
          });
          return result;
        },
        release: () => {},
      };
    } else {
      return (pgPool || (getClient() as Pool)).connect();
    }
  },
  query: async (text: string, params?: any[]) => {
    if (isVercel) {
      const client = await getVercelClient();
      return client.query({
        text,
        values: params || [],
      });
    } else {
      return (pgPool || (getClient() as Pool)).query(text, params);
    }
  },
  end: async () => {
    if (isVercel) {
      if (vercelPool?.client) {
        await vercelPool.client.end();
        vercelPool.isConnected = false;
      }
    } else if (pgPool) {
      await pgPool.end();
    }
  },
};