import { NotFoundError } from '../../lib/errors.js';
import { getCollection } from '../../lib/datastore.js';
import type {
  ListSupportCasesQuery,
  SupportCaseDoc,
  SupportCaseNoteDoc,
  SupportEscalationEventDoc,
} from './types.js';

function caseCollection() {
  return getCollection<SupportCaseDoc>('support_cases', '/productId');
}

function noteCollection() {
  return getCollection<SupportCaseNoteDoc>('support_case_notes', '/caseId');
}

function escalationCollection() {
  return getCollection<SupportEscalationEventDoc>('support_case_escalations', '/caseId');
}

export async function createCase(doc: SupportCaseDoc): Promise<SupportCaseDoc> {
  return caseCollection().create(doc);
}

export async function listCases(
  productId: string,
  query: ListSupportCasesQuery
): Promise<SupportCaseDoc[]> {
  return caseCollection().findMany({
    filter: {
      productId,
      ...(query.status ? { status: query.status } : {}),
      ...(query.priority ? { priority: query.priority } : {}),
      ...(query.source ? { source: query.source } : {}),
      ...(query.assignedTo ? { assignedTo: query.assignedTo } : {}),
    },
    sort: { createdAt: -1 },
    limit: query.limit,
  });
}

export async function getCase(id: string, productId: string): Promise<SupportCaseDoc> {
  const doc = await caseCollection().findById(id, productId);
  if (!doc) throw new NotFoundError(`Support case '${id}' not found`);
  return doc;
}

export async function updateCase(
  id: string,
  productId: string,
  updates: Partial<SupportCaseDoc>
): Promise<SupportCaseDoc> {
  const updated = await caseCollection().update(id, productId, {
    ...updates,
    updatedAt: new Date().toISOString(),
  });
  if (!updated) throw new NotFoundError(`Support case '${id}' not found`);
  return updated;
}

export async function createNote(doc: SupportCaseNoteDoc): Promise<SupportCaseNoteDoc> {
  return noteCollection().create(doc);
}

export async function listNotes(caseId: string): Promise<SupportCaseNoteDoc[]> {
  return noteCollection().findMany({
    filter: { caseId },
    sort: { createdAt: 1 },
    limit: 500,
  });
}

export async function createEscalation(
  doc: SupportEscalationEventDoc
): Promise<SupportEscalationEventDoc> {
  return escalationCollection().create(doc);
}

export async function listEscalations(caseId: string): Promise<SupportEscalationEventDoc[]> {
  return escalationCollection().findMany({
    filter: { caseId },
    sort: { createdAt: -1 },
    limit: 100,
  });
}

export async function listAllCases(productId: string, limit = 500): Promise<SupportCaseDoc[]> {
  return caseCollection().findMany({
    filter: { productId },
    sort: { createdAt: -1 },
    limit,
  });
}
