import { query } from '../../db/client.js'
import type { WorkerLevelRow } from './types.js'

export async function getWorkerLevelByKey(levelKey: string): Promise<WorkerLevelRow | null> {
  const result = await query<WorkerLevelRow>(
    'SELECT * FROM worker_levels WHERE level_key = $1 LIMIT 1',
    [String(levelKey || '').trim()],
  )
  return result.rows[0] || null
}

export async function getWorkerLevelById(levelId: number | string): Promise<WorkerLevelRow | null> {
  const result = await query<WorkerLevelRow>('SELECT * FROM worker_levels WHERE id = $1 LIMIT 1', [
    Number(levelId),
  ])
  return result.rows[0] || null
}

export async function listWorkerLevels(): Promise<WorkerLevelRow[]> {
  const result = await query<WorkerLevelRow>(
    'SELECT * FROM worker_levels ORDER BY sort_order ASC, id ASC',
  )
  return result.rows
}

export async function upsertWorkerLevel(input: {
  levelKey: string
  name: string
  sortOrder: number
  status: string
  permissionJson: string
  now: string
}): Promise<WorkerLevelRow | null> {
  const result = await query<WorkerLevelRow>(
    `INSERT INTO worker_levels (
       level_key, name, sort_order, status, permission_json, created_at, updated_at
     ) VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7)
     ON CONFLICT (level_key) DO UPDATE
     SET name = EXCLUDED.name, sort_order = EXCLUDED.sort_order, status = EXCLUDED.status,
         permission_json = EXCLUDED.permission_json, updated_at = EXCLUDED.updated_at
     RETURNING *`,
    [
      input.levelKey,
      input.name,
      input.sortOrder,
      input.status,
      input.permissionJson,
      input.now,
      input.now,
    ],
  )
  return result.rows[0] || null
}

export async function countWorkerLevelUsages(levelId: number | string): Promise<number> {
  const result = await query<{ total: number }>(
    'SELECT COUNT(*)::int AS total FROM worker_users WHERE level_id = $1',
    [Number(levelId)],
  )
  return Number(result.rows[0]?.total || 0)
}

export async function deleteWorkerLevel(levelId: number | string): Promise<{ deleted: boolean }> {
  const result = await query<{ id: number }>(
    'DELETE FROM worker_levels WHERE id = $1 RETURNING id',
    [Number(levelId)],
  )
  return { deleted: Boolean(result.rows[0]) }
}
