import { getDb } from '../db/client.js'
import { SessionStatus, TopicSensitivity } from '../constants.js'

const sql = getDb()

export const getMitraActivityLog = async ({ mitra_id, date_from, date_to, page = 1, limit = 20 } = {}) => {
  const offset = (page - 1) * limit
  const conditions = []

  if (mitra_id) conditions.push(sql`crn.mitra_id = ${mitra_id}`)
  if (date_from) conditions.push(sql`crn.notified_at >= ${date_from}`)
  if (date_to) conditions.push(sql`crn.notified_at <= ${date_to}`)

  const where = conditions.length > 0
    ? sql`WHERE ${conditions.reduce((a, b) => sql`${a} AND ${b}`)}`
    : sql``

  const items = await sql`
    SELECT crn.id, crn.session_id, crn.mitra_id, crn.response,
      crn.notified_at, crn.responded_at, crn.active_session_count,
      m.display_name AS mitra_display_name,
      cs.topic_sensitivity,
      CASE WHEN crn.responded_at IS NOT NULL
        THEN EXTRACT(EPOCH FROM (crn.responded_at - crn.notified_at))::int
        ELSE NULL
      END AS response_time_seconds
    FROM chat_request_notifications crn
    INNER JOIN mitras m ON m.id = crn.mitra_id
    LEFT JOIN chat_sessions cs ON cs.id = crn.session_id
    ${where}
    ORDER BY crn.notified_at DESC
    LIMIT ${limit} OFFSET ${offset}
  `

  const [{ count }] = await sql`
    SELECT COUNT(*) FROM chat_request_notifications crn ${where}
  `

  return { items, total: Number(count), page, limit }
}

export const getRecentRequestsForMitra = async (mitraId, { limit = 20 } = {}) => {
  const cap = Math.min(Math.max(1, Number(limit) || 20), 20)
  const items = await sql`
    SELECT
      crn.id              AS notification_id,
      crn.session_id,
      crn.notified_at,
      crn.responded_at,
      crn.response,
      cs.status           AS session_status,
      cs.topic_sensitivity,
      COALESCE(NULLIF(trim(c.display_name), ''), 'Anonim') AS customer_call_name
    FROM chat_request_notifications crn
    LEFT JOIN chat_sessions cs ON cs.id = crn.session_id
    LEFT JOIN customers c      ON c.id = cs.customer_id
    WHERE crn.mitra_id = ${mitraId}
    ORDER BY
      (crn.response IS NULL AND cs.status = ${SessionStatus.PENDING_ACCEPTANCE}) DESC,
      crn.notified_at DESC
    LIMIT ${cap}
  `
  return items
}

export const getMitraActivitySummary = async ({ mitra_id, date_from, date_to } = {}) => {
  const conditions = []

  if (mitra_id) conditions.push(sql`crn.mitra_id = ${mitra_id}`)
  if (date_from) conditions.push(sql`crn.notified_at >= ${date_from}`)
  if (date_to) conditions.push(sql`crn.notified_at <= ${date_to}`)

  const where = conditions.length > 0
    ? sql`WHERE ${conditions.reduce((a, b) => sql`${a} AND ${b}`)}`
    : sql``

  const summaries = await sql`
    SELECT crn.mitra_id,
      m.display_name AS mitra_display_name,
      COUNT(*)::int AS total_requests,
      COUNT(*) FILTER (WHERE crn.response = 'accepted')::int AS accepted_count,
      COUNT(*) FILTER (WHERE crn.response = 'declined')::int AS rejected_count,
      COUNT(*) FILTER (WHERE crn.response = 'missed')::int AS missed_count,
      COUNT(*) FILTER (WHERE crn.response = 'ignored')::int AS ignored_count,
      ROUND(
        100.0 * COUNT(*) FILTER (WHERE crn.response = 'accepted') / NULLIF(COUNT(*), 0), 1
      ) AS acceptance_rate,
      AVG(
        CASE WHEN crn.responded_at IS NOT NULL
          THEN EXTRACT(EPOCH FROM (crn.responded_at - crn.notified_at))
          ELSE NULL
        END
      )::numeric(10,1) AS avg_response_time_seconds,
      COUNT(*) FILTER (WHERE cs.topic_sensitivity = ${TopicSensitivity.SENSITIVE})::int AS sensitive_total,
      COUNT(*) FILTER (WHERE cs.topic_sensitivity = ${TopicSensitivity.SENSITIVE} AND crn.response = 'accepted')::int AS sensitive_accepted,
      COUNT(*) FILTER (WHERE cs.topic_sensitivity = ${TopicSensitivity.SENSITIVE} AND crn.response = 'declined')::int AS sensitive_rejected,
      ROUND(
        100.0 * COUNT(*) FILTER (WHERE cs.topic_sensitivity = ${TopicSensitivity.SENSITIVE} AND crn.response = 'accepted')
        / NULLIF(COUNT(*) FILTER (WHERE cs.topic_sensitivity = ${TopicSensitivity.SENSITIVE}), 0), 1
      ) AS sensitive_acceptance_rate
    FROM chat_request_notifications crn
    INNER JOIN mitras m ON m.id = crn.mitra_id
    LEFT JOIN chat_sessions cs ON cs.id = crn.session_id
    ${where}
    GROUP BY crn.mitra_id, m.display_name
    ORDER BY acceptance_rate DESC NULLS LAST
  `

  return summaries
}
