import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
import { IPostRepository } from '../Domain/IPostRepository.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const POST_FILE = path.join(__dirname, 'post.json');

export class PostRepository extends IPostRepository {
  async getAll() {
    try {
      const data = await fs.readFile(POST_FILE, 'utf-8');
      return JSON.parse(data);
    } catch (error) {
      return [];
    }
  }

  async getById(id) {
    const posts = await this.getAll();
    return posts.find(post => post.id === id);
  }

  async getByUserId(userId) {
    const posts = await this.getAll();
    return posts.filter(post => post.userId === userId);
  }

  async create(post) {
    const posts = await this.getAll();
    const newPost = {
      id: Date.now().toString(),
      ...post,
      createdAt: new Date().toISOString()
    };
    posts.push(newPost);
    await fs.writeFile(POST_FILE, JSON.stringify(posts, null, 2));
    return newPost;
  }

  async update(id, postData) {
    const posts = await this.getAll();
    const index = posts.findIndex(post => post.id === id);
    if (index === -1) return null;
    
    posts[index] = {
      ...posts[index],
      ...postData,
      id: posts[index].id,
      updatedAt: new Date().toISOString()
    };
    await fs.writeFile(POST_FILE, JSON.stringify(posts, null, 2));
    return posts[index];
  }

  async delete(id) {
    const posts = await this.getAll();
    const filteredPosts = posts.filter(post => post.id !== id);
    if (posts.length === filteredPosts.length) return false;
    
    await fs.writeFile(POST_FILE, JSON.stringify(filteredPosts, null, 2));
    return true;
  }
}
