import { z } from 'zod';
import { BadRequestError } from './errors';

/**
 * Opt-in pagination for list endpoints.
 *
 * Both clients read the existing unpaginated shape, so a request without
 * `page` or `limit` must keep returning the plain array it always did. Only
 * when a client asks for a page does the response become an envelope — which
 * is what makes this safe to deploy ahead of the clients.
 */
export const paginationSchema = z.object({
  page: z.coerce.number().int().min(1).optional(),
  // Capped so a client cannot ask for the whole table in one request.
  limit: z.coerce.number().int().min(1).max(100).optional(),
});

/**
 * Free-text search, shared by every list that offers it.
 *
 * Searching and filtering belong here rather than in a client: once a list is
 * paginated the client only holds one page, so filtering locally would search
 * the page instead of the table.
 */
export const searchSchema = z.object({
  q: z.string().trim().min(1).max(100).optional(),
});

export function getSearch(query: unknown): string | undefined {
  const parsed = searchSchema.safeParse(query);
  return parsed.success ? parsed.data.q : undefined;
}

export interface Pagination {
  page: number;
  limit: number;
  skip: number;
}

export interface Paginated<T> {
  items: T[];
  total: number;
  page: number;
  limit: number;
  /** Saves every client recomputing `page * limit < total`. */
  hasMore: boolean;
}

const DEFAULT_LIMIT = 25;

/**
 * Reads pagination off a query string. Returns null when the caller asked for
 * neither, which is the signal to answer with the legacy array.
 *
 * Throws on an out-of-range value rather than falling back: a `limit=500`
 * that quietly returned the unpaginated list would defeat the cap entirely,
 * handing back the whole table instead of refusing.
 */
export function getPagination(query: unknown): Pagination | null {
  // `page` is the signal, not `limit`. The punches endpoint already took a
  // `limit` to mean "the most recent N", and treating that as a page request
  // silently changed its response shape for every existing caller.
  const asked = typeof query === 'object' && query !== null && 'page' in query;
  if (!asked) return null;

  const parsed = paginationSchema.safeParse(query);
  if (!parsed.success) {
    throw new BadRequestError('page must be at least 1 and limit between 1 and 100');
  }

  const { page, limit } = parsed.data;
  if (page === undefined) return null;

  const resolvedPage = page ?? 1;
  const resolvedLimit = limit ?? DEFAULT_LIMIT;
  return {
    page: resolvedPage,
    limit: resolvedLimit,
    skip: (resolvedPage - 1) * resolvedLimit,
  };
}

export function paginated<T>(
  items: T[],
  total: number,
  pagination: Pagination,
): Paginated<T> {
  return {
    items,
    total,
    page: pagination.page,
    limit: pagination.limit,
    hasMore: pagination.skip + items.length < total,
  };
}
