import { readJson, writeJson } from './storage';
import { randomUUID } from 'node:crypto';

export type Submission = {
  id: string;
  name: string;
  dog: string;
  phone: string;
  message: string;
  createdAt: string;
  ip?: string;
};

const FILE = 'submissions.json';

export function listSubmissions(): Submission[] {
  const items = readJson<Submission[]>(FILE, []);
  return [...items].sort((a, b) => b.createdAt.localeCompare(a.createdAt));
}

export function addSubmission(input: Omit<Submission, 'id' | 'createdAt'>): Submission {
  const items = readJson<Submission[]>(FILE, []);
  const entry: Submission = {
    id: randomUUID(),
    createdAt: new Date().toISOString(),
    ...input
  };
  items.push(entry);
  writeJson(FILE, items);
  return entry;
}

export function deleteSubmission(id: string): void {
  const items = readJson<Submission[]>(FILE, []);
  writeJson(FILE, items.filter((s) => s.id !== id));
}
