import { rpcOrEmptyArray, rpcOrValue } from './rpc.uts'

export type CustomReportListItem = {
  id: string
  title: string
  description: string
  period: string
  updated_at: string
}

export type CreateCustomReportParams = {
  title: string
  description: string
  period: string
  metrics: Array<string>
  chartType: string
}

export type UpdateCustomReportParams = {
  reportId: string
  title: string
  description: string | null
  period: string | null
}

function safeString(v: any): string {
  return v != null ? `${v}` : ''
}

// 改造：不再直查 analytics_reports 表，统一通过 RPC 获取当前用户的报表列表
export async function listCustomReports(ownerUserId: string): Promise<Array<CustomReportListItem>> {
  // rpc_get_custom_reports 基于 auth.uid() 过滤，无需额外参数，这里保留签名用于兼容调用方
  const rows = await rpcOrEmptyArray('rpc_get_custom_reports', {} as any)
  const list: Array<CustomReportListItem> = []
  for (let i = 0; i < rows.length; i++) {
    const r: any = rows[i]
    list.push({
      id: safeString(r.getAny?.('id') ?? r.getString?.('id')),
      title: safeString(r.getAny?.('title') ?? r.getString?.('title')),
      description: safeString(r.getAny?.('description') ?? r.getString?.('description')),
      period: safeString(r.getAny?.('period') ?? r.getString?.('period')),
      updated_at: safeString(r.getAny?.('updated_at') ?? r.getString?.('updated_at'))
    })
  }
  return list
}

// 改造：RPC 参数改为 p_definition（JSONB），承载 period/metrics/chartType
export async function createCustomReport(params: CreateCustomReportParams): Promise<string> {
  const definition = {
    period: params.period,
    metrics: params.metrics,
    chartType: params.chartType || 'line'
  }

  const data = await rpcOrValue('rpc_create_custom_report', {
    p_title: params.title,
    p_description: params.description || '',
    p_definition: definition
  } as any)

  if (data == null) {
    throw new Error('保存失败：未返回报表ID')
  }

  return `${data}`
}

export async function updateCustomReport(params: UpdateCustomReportParams): Promise<boolean> {
  // 注意：旧 UI 只传 title/description/period，这里把 period 合并进 definition
  const definition = {
    period: params.period
  }

  await rpcOrValue('rpc_update_custom_report', {
    p_report_id: params.reportId,
    p_title: params.title,
    p_description: params.description,
    p_definition: definition
  } as any)

  return true
}

export async function deleteCustomReport(reportId: string): Promise<boolean> {
  await rpcOrValue('rpc_delete_custom_report', {
    p_report_id: reportId
  } as any)

  return true
}
