import adminClient from "./client"
import type { ApiResponse } from "../../types"
import { listResult, pageResult } from "./response"

const BASE = "/v1/admin"

export interface AdminAgentTier {
  id: number
  name: string
  code: string
  cost_rate: number
  min_member_level: number
  min_total_spend: number
  monthly_sales_required: number
  monthly_active_customers_required: number
  max_refund_rate_bps: number
  max_monthly_subsidy_cents: number
  min_balance_for_subsidy_cents: number
  observe_days: number
  freeze_days: number
  auto_downgrade_enabled: boolean
  max_coupon_discount_rate: number
  max_monthly_coupon_count: number
  sort_order: number
  enabled: boolean
  description: string | null
  created_at: string
}

export interface AdminAgentItem {
  id: number
  user_id: number
  agent_tier_id: number | null
  status: string
  invite_code: string | null
  total_sales: number
  total_profit: number
  total_subsidy: number
  agent_balance: number
  agent_frozen_balance: number
  approved_at: string | null
  observe_started_at: string | null
  observe_until: string | null
  risk_locked_at: string | null
  risk_reason: string | null
  last_evaluated_at: string | null
  last_evaluation_snapshot: Record<string, unknown> | null
  reject_reason: string | null
  remark: string | null
  review_message: string | null
  created_at: string
  agent_tier: AdminAgentTier | null
  apply_tier: string | null
  apply_reason: string | null
  apply_channels: string | null
  user: {
    id: number
    username: string
    email: string | null
    nickname: string | null
    phone: string | null
    balance: number
    created_at: string
  } | null
}

export interface AgentEvaluationLog {
  id: number
  net_sales: number
  gross_sales: number
  refund_amount: number
  refund_rate_bps: number
  active_customers: number
  subsidy_loss: number
  agent_balance: number
  passed: boolean
  risk_locked: boolean
  action: string
  reason: string | null
  created_at: string | null
}

export interface AgentStatusLog {
  id: number
  source: string
  action: string
  before_status: string | null
  after_status: string | null
  before_tier_id: number | null
  after_tier_id: number | null
  reason: string | null
  operator_id: number | null
  created_at: string | null
}

export interface AgentRiskEvent {
  id: number
  event_type: string
  severity: string
  status: string
  reason: string | null
  created_at: string | null
}

export interface AdminAgentDetail extends AdminAgentItem {
  tickets: AgentTicketInfo[]
  evaluation_logs: AgentEvaluationLog[]
  status_logs: AgentStatusLog[]
  risk_events: AgentRiskEvent[]
}

export async function listAgentTiers(): Promise<ApiResponse<AdminAgentTier[]>> {
  const { data } = await adminClient.get<ApiResponse<AdminAgentTier[] | { items: AdminAgentTier[]; total: number }>>(`${BASE}/agent-tiers`)
  return { ...data, data: listResult<AdminAgentTier>(data.data) }
}

export async function createAgentTier(payload: Partial<AdminAgentTier>): Promise<ApiResponse<AdminAgentTier>> {
  const { data } = await adminClient.post<ApiResponse<AdminAgentTier>>(`${BASE}/agent-tiers`, payload)
  return data
}

export async function updateAgentTier(id: number, payload: Partial<AdminAgentTier>): Promise<ApiResponse<AdminAgentTier>> {
  const { data } = await adminClient.put<ApiResponse<AdminAgentTier>>(`${BASE}/agent-tiers/${id}`, payload)
  return data
}

export async function deleteAgentTier(id: number): Promise<ApiResponse<{ ok: boolean }>> {
  const { data } = await adminClient.delete<ApiResponse<{ ok: boolean }>>(`${BASE}/agent-tiers/${id}`)
  return data
}

export async function listAgents(params?: { filter_status?: string; keyword?: string; offset?: number; limit?: number }): Promise<ApiResponse<{ items: AdminAgentItem[]; total: number }>> {
  const { data } = await adminClient.get<ApiResponse<{ items: AdminAgentItem[]; total: number } | AdminAgentItem[]>>(`${BASE}/agents`, { params })
  return { ...data, data: pageResult<AdminAgentItem>(data.data) }
}

export async function reviewAgent(id: number, payload: { action: string; agent_tier_id?: number; reject_reason?: string; remark?: string }): Promise<ApiResponse<AdminAgentItem>> {
  const { data } = await adminClient.post<ApiResponse<AdminAgentItem>>(`${BASE}/agents/${id}/review`, payload)
  return data
}

export async function assignAgentTier(id: number, agent_tier_id: number): Promise<ApiResponse<AdminAgentItem>> {
  const { data } = await adminClient.put<ApiResponse<AdminAgentItem>>(`${BASE}/agents/${id}/tier`, { agent_tier_id })
  return data
}

export async function evaluateAgent(id: number): Promise<ApiResponse<{ agent: AdminAgentItem; evaluation: Record<string, unknown> }>> {
  const { data } = await adminClient.post<ApiResponse<{ agent: AdminAgentItem; evaluation: Record<string, unknown> }>>(`${BASE}/agents/${id}/evaluate`)
  return data
}

export async function manualAgentAction(
  id: number,
  payload: { action: string; reason: string; agent_tier_id?: number },
): Promise<ApiResponse<AdminAgentItem>> {
  const { data } = await adminClient.post<ApiResponse<AdminAgentItem>>(`${BASE}/agents/${id}/action`, payload)
  return data
}

export async function listAgentSettlements(params?: {
  settlement_type?: string
  status?: string
  user_id?: number
  order_id?: number
  offset?: number
  limit?: number
}): Promise<ApiResponse<{ items: unknown[]; total: number }>> {
  const { data } = await adminClient.get<ApiResponse<{ items: unknown[]; total: number } | unknown[]>>(`${BASE}/agent-settlements`, { params })
  return { ...data, data: pageResult<unknown>(data.data) }
}

export interface AffiliateChannelItem {
  aff_code: string
  utm_source: string | null
  utm_medium: string | null
  utm_campaign: string | null
  clicks: number
  registrations: number
  orders: number
  revenue: number
  register_rate_bps: number
  order_rate_bps: number
  latest_click_at: string | null
}

export interface AffiliateClickItem {
  id: number
  aff_code: string
  agent_id: number | null
  landing_url: string | null
  ip: string | null
  referer: string | null
  utm_source: string | null
  utm_medium: string | null
  utm_campaign: string | null
  utm_content: string | null
  utm_term: string | null
  registered_user_id: number | null
  converted_at: string | null
  created_at: string | null
}

export interface AffiliateReport {
  summary: {
    clicks: number
    unique_ips: number
    registrations: number
    paid_orders: number
    revenue: number
    register_rate_bps: number
    order_rate_bps: number
  }
  channels: AffiliateChannelItem[]
  recent_clicks: AffiliateClickItem[]
}

export async function getAffiliateReport(params?: { recent_limit?: number; max_rows?: number }): Promise<ApiResponse<AffiliateReport>> {
  const { data } = await adminClient.get<ApiResponse<AffiliateReport>>(`${BASE}/affiliate/report`, { params })
  return data
}

export interface AgentTicketMessage {
  id: number
  content: string
  sender_type: string
  created_at: string | null
}

export interface AgentTicketInfo {
  ticket_id: number
  ticket_no: string
  subject: string
  status: string
  created_at: string | null
  messages: AgentTicketMessage[]
}

export async function getAgentDetail(id: number): Promise<ApiResponse<AdminAgentDetail>> {
  const { data } = await adminClient.get<ApiResponse<AdminAgentDetail>>(`${BASE}/agents/${id}`)
  return data
}
