import { v4 as uuidv4 } from "uuid";
import { logger } from "../utils/logger";

export interface SampleItem {
  id: string;
  name: string;
  description: string;
  is_deleted: boolean;
  created_at: string;
  updated_at: string;
}

// 인메모리 저장소 (실제 DB 테이블 없이도 동작)
const store = new Map<string, SampleItem>();

export class SampleService {
  private static instance: SampleService;

  private constructor() {}

  public static getInstance(): SampleService {
    if (!SampleService.instance) {
      SampleService.instance = new SampleService();
    }
    return SampleService.instance;
  }

  /**
   * 목록 조회 (페이징, soft delete 제외)
   */
  public async getList(page: number, limit: number): Promise<{ items: SampleItem[]; total: number }> {
    const active = Array.from(store.values()).filter((item) => !item.is_deleted);
    const total = active.length;
    const items = active.slice((page - 1) * limit, page * limit);
    logger.info(`📋 sample 목록 조회: total=${total}, page=${page}, limit=${limit}`);
    return { items, total };
  }

  /**
   * 등록
   */
  public async create(name: string, description: string): Promise<SampleItem> {
    const now = new Date().toISOString();
    const item: SampleItem = {
      id: uuidv4(),
      name,
      description,
      is_deleted: false,
      created_at: now,
      updated_at: now,
    };
    store.set(item.id, item);
    logger.info(`✅ sample 등록: ${item.id}`);
    return item;
  }

  /**
   * 수정
   */
  public async update(id: string, name?: string, description?: string): Promise<SampleItem> {
    const item = store.get(id);
    if (!item || item.is_deleted) {
      throw new Error(`항목을 찾을 수 없습니다: ${id}`);
    }
    if (name !== undefined) item.name = name;
    if (description !== undefined) item.description = description;
    item.updated_at = new Date().toISOString();
    store.set(id, item);
    logger.info(`✅ sample 수정: ${id}`);
    return item;
  }

  /**
   * Soft delete
   */
  public async softDelete(id: string): Promise<void> {
    const item = store.get(id);
    if (!item || item.is_deleted) {
      throw new Error(`항목을 찾을 수 없습니다: ${id}`);
    }
    item.is_deleted = true;
    item.updated_at = new Date().toISOString();
    store.set(id, item);
    logger.info(`✅ sample 삭제(soft): ${id}`);
  }
}
