import { localDataSource } from '../LocalDataSource';
import type { ILocalDataSource } from '@/data/datasources/interfaces';

export interface IPostCacheRepository {
  save(id: string, data: any): Promise<void>;
  get(id: string): Promise<any | null>;
  getAll(): Promise<any[]>;
  delete(id: string): Promise<void>;
}

export class PostCacheRepository implements IPostCacheRepository {
  constructor(private dataSource: ILocalDataSource = localDataSource) {}

  async save(id: string, data: any): Promise<void> {
    await this.dataSource.enqueueWrite(async () => {
      await this.dataSource.run(
        `INSERT OR REPLACE INTO posts_cache (id, data, updatedAt) VALUES (?, ?, ?)`,
        [String(id), JSON.stringify(data), new Date().toISOString()]
      );
    });
  }

  async get(id: string): Promise<any | null> {
    const r = await this.dataSource.getFirst<{ data: string }>(
      `SELECT data FROM posts_cache WHERE id = ?`, [String(id)]
    );
    return r?.data ? JSON.parse(r.data) : null;
  }

  async getAll(): Promise<any[]> {
    const rows = await this.dataSource.query<{ data: string }>(
      `SELECT data FROM posts_cache ORDER BY updatedAt DESC`
    );
    return rows.map(r => JSON.parse(r.data));
  }

  async delete(id: string): Promise<void> {
    await this.dataSource.enqueueWrite(async () => {
      await this.dataSource.run(`DELETE FROM posts_cache WHERE id = ?`, [String(id)]);
    });
  }
}

export const postCacheRepository = new PostCacheRepository();