import type { RequirementScopeSelection } from './requirement-scope';
import type { RequirementDateSort } from './requirement-sort';
import type { V22RequirementsQuery } from './v22-api';

export interface RequirementV22ProjectRef {
  id: string;
  productId: string;
}

export interface BuildV22RequirementQueryInput {
  selectedScope: RequirementScopeSelection;
  projects: RequirementV22ProjectRef[];
  statusFilter: string;
  priorityFilter: string;
  typeFilter: string;
  versionFilter: string;
  search: string;
  dateSort: RequirementDateSort;
  limit: number;
  cursor?: string;
}

export function buildV22RequirementQuery(input: BuildV22RequirementQueryInput): V22RequirementsQuery | undefined {
  if (input.statusFilter === 'dev_completed') return undefined;

  const scoped = getPartitionScope(input.selectedScope, input.projects);
  if (!scoped) return undefined;

  return compactQuery({
    ...scoped,
    status: input.statusFilter === 'all' ? undefined : input.statusFilter,
    priority: input.priorityFilter === 'all' ? undefined : input.priorityFilter,
    type: input.typeFilter === 'all' ? undefined : input.typeFilter,
    versionId: input.versionFilter === 'all' ? undefined : input.versionFilter,
    q: input.search.trim() || undefined,
    sort: input.dateSort === 'asc' ? 'created_at_asc' : 'created_at_desc',
    cursor: input.cursor,
    limit: input.limit,
  });
}

function getPartitionScope(
  selectedScope: RequirementScopeSelection,
  projects: RequirementV22ProjectRef[],
): Pick<V22RequirementsQuery, 'productId' | 'projectId'> | undefined {
  if (selectedScope.type === 'product') {
    const productId = selectedScope.productId.trim();
    return productId ? { productId } : undefined;
  }

  if (selectedScope.type === 'project') {
    const projectId = selectedScope.projectId.trim();
    const project = projects.find((item) => item.id === projectId);
    if (!project?.productId) return undefined;
    return { productId: project.productId, projectId };
  }

  return undefined;
}

function compactQuery(query: V22RequirementsQuery): V22RequirementsQuery {
  const result: V22RequirementsQuery = { productId: query.productId };
  if (query.projectId) result.projectId = query.projectId;
  if (query.versionId) result.versionId = query.versionId;
  if (query.status) result.status = query.status;
  if (query.priority) result.priority = query.priority;
  if (query.type) result.type = query.type;
  if (query.q) result.q = query.q;
  if (query.sort) result.sort = query.sort;
  if (query.cursor) result.cursor = query.cursor;
  if (query.limit) result.limit = query.limit;
  return result;
}
