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

export async function getWorkCategoryByKey(categoryKey: string): Promise<WorkCategoryRow | null> {
  const result = await query<WorkCategoryRow>(
    'SELECT * FROM work_categories WHERE category_key = $1 LIMIT 1',
    [String(categoryKey || '').trim()],
  )
  return result.rows[0] || null
}

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

export async function listWorkCategories(): Promise<WorkCategoryRow[]> {
  const result = await query<WorkCategoryRow>(
    `SELECT * FROM work_categories WHERE status = 'active' ORDER BY sort_order ASC, id ASC`,
  )
  return result.rows
}

export async function listAllWorkCategories(): Promise<WorkCategoryRow[]> {
  const result = await query<WorkCategoryRow>(
    `SELECT * FROM work_categories ORDER BY sort_order ASC, id ASC`,
  )
  return result.rows
}

export async function upsertWorkCategory(input: {
  categoryKey: string
  name: string
  sortOrder: number
  status: string
  now: string
}): Promise<WorkCategoryRow | null> {
  const result = await query<WorkCategoryRow>(
    `
      INSERT INTO work_categories (category_key, name, sort_order, status, created_at, updated_at)
      VALUES ($1, $2, $3, $4, $5, $6)
      ON CONFLICT (category_key) DO UPDATE
      SET name = EXCLUDED.name, sort_order = EXCLUDED.sort_order, status = EXCLUDED.status, updated_at = EXCLUDED.updated_at
      RETURNING *
    `,
    [input.categoryKey, input.name, input.sortOrder, input.status, input.now, input.now],
  )
  return result.rows[0] || null
}

export async function countWorkCategoryUsages(categoryId: number | string): Promise<{
  workOrderCount: number
  productRuleCount: number
}> {
  const [orders, rules] = await Promise.all([
    query<{ total: number }>(
      'SELECT COUNT(*)::int AS total FROM work_orders WHERE category_id = $1',
      [Number(categoryId)],
    ),
    query<{ total: number }>(
      'SELECT COUNT(*)::int AS total FROM work_product_rules WHERE category_id = $1',
      [Number(categoryId)],
    ),
  ])
  return {
    workOrderCount: Number(orders.rows[0]?.total || 0),
    productRuleCount: Number(rules.rows[0]?.total || 0),
  }
}

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