import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'
import type { ProductComment } from '../types/comment'

export const COMMENTS_PER_PAGE = 12

export interface CommentApi {
  id: string
  businessId: string
  entityType: string
  entityId: string
  authorName: string
  authorEmail: string | null
  text: string
  isApproved: boolean
  approvedAt: string | null
  approvedBy: string | null
  approver: { id: string; firstName: string; lastName: string } | null
  createdAt: string
  updatedAt: string
}

export interface CommentsListResponse {
  items: CommentApi[]
  total: number
  page: number
  pageSize: number
}

function commentsPath(suffix = '') {
  const businessId = getActiveBusinessId()
  if (!businessId) {
    throw new Error('No active business selected. Please sign in again.')
  }
  return `/businesses/${businessId}/comments${suffix}`
}

export function mapCommentApiToUi(comment: CommentApi): ProductComment {
  return {
    id: comment.id,
    author: comment.authorName,
    createdAt: comment.createdAt,
    text: comment.text,
    likesCount: 0,
    approved: comment.isApproved,
  }
}

async function listEntityComments(
  entityType: 'product' | 'blog' | 'portfolio',
  entityId: string,
  page = 1,
  pageSize = COMMENTS_PER_PAGE,
  signal?: AbortSignal,
) {
  const params = new URLSearchParams({
    entityType,
    entityId,
    page: String(page),
    pageSize: String(pageSize),
  })

  const data = await apiRequest<CommentsListResponse>(`${commentsPath()}?${params}`, {
    auth: true,
    signal,
  })

  return {
    ...data,
    items: data.items.map(mapCommentApiToUi),
  }
}

export async function listProductComments(
  productId: string,
  page = 1,
  pageSize = COMMENTS_PER_PAGE,
  signal?: AbortSignal,
) {
  return listEntityComments('product', productId, page, pageSize, signal)
}

export async function listBlogComments(
  blogId: string,
  page = 1,
  pageSize = COMMENTS_PER_PAGE,
  signal?: AbortSignal,
) {
  return listEntityComments('blog', blogId, page, pageSize, signal)
}

export async function listPortfolioComments(
  portfolioId: string,
  page = 1,
  pageSize = COMMENTS_PER_PAGE,
  signal?: AbortSignal,
) {
  return listEntityComments('portfolio', portfolioId, page, pageSize, signal)
}

export async function updateCommentApproval(commentId: string, isApproved: boolean) {
  const data = await apiRequest<{ comment: CommentApi }>(commentsPath(`/${commentId}`), {
    method: 'PATCH',
    auth: true,
    body: { isApproved },
  })
  return mapCommentApiToUi(data.comment)
}

export async function deleteComment(commentId: string) {
  return apiRequest<{ message: string }>(commentsPath(`/${commentId}`), {
    method: 'DELETE',
    auth: true,
  })
}
