File size: 2,712 Bytes
9853b20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
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
import { Pool } from 'pg'
import { randomUUID } from 'crypto'
import { createServiceClient } from './supabase/server'

type LogLevel = 'all' | 'light' | 'mini' | 'off'

const level = (process.env.LOG_LEVEL as LogLevel) || 'light'
const LOCAL_DB_URL = process.env.LOCAL_DATABASE_URL

let pool: Pool | null = null
let logsTableReady = false

if (LOCAL_DB_URL) {
  pool = new Pool({ connectionString: LOCAL_DB_URL })
}

async function ensureLogsTable() {
  if (!pool || logsTableReady) return
  try {
    await pool.query(`
      CREATE TABLE IF NOT EXISTS logs (
        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        created_at TIMESTAMP DEFAULT NOW(),
        lang VARCHAR,
        ip VARCHAR,
        user_agent VARCHAR,
        module VARCHAR,
        operation VARCHAR,
        data JSONB,
        error TEXT,
        level VARCHAR
      );
    `)
    logsTableReady = true
  } catch (e) {
    console.error('[logger] Failed to ensure logs table:', e)
  }
}

export interface LogPayload {
  module: string
  operation: string
  data?: Record<string, any> | null
  error?: string | null
  ip?: string | null
  userAgent?: string | null
  lang?: string | null
}

export async function logEvent(payload: LogPayload) {
  if (level === 'off') return

  const shouldIncludeUA = level === 'all'
  const shouldIncludeData = level === 'all'

  const row = {
    id: randomUUID(),
    created_at: new Date().toISOString(),
    lang: payload.lang ?? null,
    ip: payload.ip ?? null,
    user_agent: shouldIncludeUA ? payload.userAgent ?? null : null,
    module: payload.module,
    operation: payload.operation,
    data: shouldIncludeData ? payload.data ?? null : null,
    error: payload.error ?? null,
    level
  }

  // Prefer local DB
  if (pool) {
    await ensureLogsTable()
    try {
      await pool.query(
        'INSERT INTO logs(id, created_at, lang, ip, user_agent, module, operation, data, error, level) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)',
        [row.id, row.created_at, row.lang, row.ip, row.user_agent, row.module, row.operation, row.data, row.error, row.level]
      )
      return
    } catch (e) {
      console.error('[logger] Failed to insert log into local DB:', e)
    }
  }

  // Fallback to Supabase service-role if available
  try {
    if (process.env.SUPABASE_SERVICE_ROLE_KEY && process.env.SUPABASE_URL) {
      const supabase = await createServiceClient()
      // logs table není v generovaných typech; vlož jako any
      await supabase.from('logs' as any).insert(row as any)
      return
    }
  } catch (e) {
    console.error('[logger] Failed to insert log into Supabase:', e)
  }

  // Fallback to in-memory/console
  console.info('[logger] (fallback)', row)
}