import { IPagination, IPaginationOptions } from '@/types'

export function getPaginationData(pagination: IPaginationOptions): IPagination {
	const { limit, page, pages, total } = pagination

	const hasPrevPage = page > 0
	const hasNextPage = page < pages - 1

	const pageNumbers = generatePageNumbers(page, pages)

	return {
		limit,
		page,
		pages,
		total,
		hasPrevPage,
		hasNextPage,
		pageNumbers
	}
}

////////////

function generatePageNumbers(
	currentPage: number,
	totalPages: number
): (number | 'ellipsis')[] {
	if (totalPages <= 7) {
		return Array.from({ length: totalPages }, (_, i) => i + 1)
	}

	const result: (number | 'ellipsis')[] = []

	result.push(1)

	if (totalPages === 8) {
		if (currentPage < 4) {
			result.push(2, 3, 4, 5)
			result.push('ellipsis')
			result.push(8)
		} else {
			result.push('ellipsis')
			result.push(4, 5, 6, 7, 8)
		}
		return result
	}

	if (totalPages === 9) {
		if (currentPage <= 4) {
			result.push(2, 3, 4, 5)
			result.push('ellipsis')
			result.push(9)
		} else if (currentPage === 5) {
			result.push('ellipsis', 3, 4, 5, 6, 7, 'ellipsis', 9)
		} else {
			result.push('ellipsis')
			result.push(5, 6, 7, 8, 9)
		}
		return result
	}

	if (totalPages === 10) {
		if (currentPage <= 4) {
			result.push(2, 3, 4, 5)
			result.push('ellipsis')
			result.push(10)
		} else if (currentPage === 5) {
			result.push('ellipsis', 3, 4, 5, 6, 7, 'ellipsis', 10)
		} else if (currentPage === 6) {
			result.push('ellipsis', 4, 5, 6, 7, 8, 'ellipsis', 10)
		} else {
			result.push('ellipsis')
			result.push(6, 7, 8, 9, 10)
		}
		return result
	}

	if (totalPages === 11) {
		if (currentPage <= 4) {
			result.push(2, 3, 4, 5)
			result.push('ellipsis')
			result.push(11)
		} else if (currentPage >= 5 && currentPage <= 7) {
			result.push('ellipsis')
			result.push(
				currentPage - 2,
				currentPage - 1,
				currentPage,
				currentPage + 1,
				currentPage + 2
			)
			result.push('ellipsis')
			result.push(11)
		} else {
			result.push('ellipsis')
			result.push(7, 8, 9, 10, 11)
		}
		return result
	}

	if (currentPage <= 4) {
		result.push(2, 3, 4, 5)
		result.push('ellipsis')
		result.push(totalPages)
	} else if (currentPage >= totalPages - 3) {
		result.push('ellipsis')
		result.push(
			totalPages - 4,
			totalPages - 3,
			totalPages - 2,
			totalPages - 1,
			totalPages
		)
	} else {
		result.push('ellipsis')
		result.push(
			currentPage - 2,
			currentPage - 1,
			currentPage,
			currentPage + 1,
			currentPage + 2
		)
		result.push('ellipsis')
		result.push(totalPages)
	}

	return result
}

////////////

export function getRangePagination(
	pagination: IPaginationOptions
): Record<string, number> {
	const { page, limit, total } = pagination
	//
	const startIndex = page * limit
	const endIndex = Math.min((page + 1) * limit, total)
	//
	return {
		from: startIndex + 1,
		to: endIndex
	}
}
