import type { Appeal, AppealStatus } from "@/types";
import { appeals as seed } from "@/features/_mock/extra";

let store = [...seed];

export const appealsService = {
  async list(playerId?: string): Promise<Appeal[]> {
    return playerId ? store.filter((a) => a.playerId === playerId) : [...store];
  },
  async get(id: string) { return store.find((a) => a.id === id) ?? null; },
  async hasOpenFor(punishmentId: string, playerId: string) {
    return store.some(
      (a) => a.punishmentId === punishmentId && a.playerId === playerId &&
        !["approved", "rejected", "closed"].includes(a.status),
    );
  },
  async submit(data: Omit<Appeal, "id" | "status" | "createdAt" | "updatedAt" | "messages" | "timeline">): Promise<Appeal> {
    const now = new Date().toISOString().slice(0, 16).replace("T", " ");
    const appeal: Appeal = {
      ...data, id: `ap-${Date.now()}`, status: "submitted",
      createdAt: now, updatedAt: now, messages: [],
      timeline: [{ time: now, label: "Appeal submitted" }],
    };
    store = [appeal, ...store];
    return appeal;
  },
  async setStatus(id: string, status: AppealStatus, note?: string): Promise<Appeal> {
    const now = new Date().toISOString().slice(0, 16).replace("T", " ");
    store = store.map((a) => a.id === id ? {
      ...a, status, updatedAt: now,
      timeline: [...a.timeline, { time: now, label: `Status → ${status}${note ? ` — ${note}` : ""}` }],
    } : a);
    return store.find((a) => a.id === id)!;
  },
  async assign(id: string, admin: string) {
    store = store.map((a) => a.id === id ? { ...a, assignedAdmin: admin } : a);
    return store.find((a) => a.id === id)!;
  },
  async reply(id: string, body: string, role: "player" | "admin", author: string) {
    const now = new Date().toISOString().slice(0, 16).replace("T", " ");
    store = store.map((a) => a.id === id ? {
      ...a, updatedAt: now,
      messages: [...a.messages, { id: `m-${Date.now()}`, author, role, time: now, body }],
    } : a);
    return store.find((a) => a.id === id)!;
  },
};