package com.example.myapplication.repository;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.myapplication.domain.Comment;

import java.util.ArrayList;
import java.util.List;

public class CommentRepository {
    private final Context context;
    private DatabaseHelper helper;
    private SQLiteDatabase db;

    public CommentRepository(Context context) { this.context = context.getApplicationContext(); }

    public void openDatabase() {
        if (helper == null) helper = new DatabaseHelper(context);
        if (db == null || !db.isOpen()) db = helper.getWritableDatabase();
    }

    public void closeDatabase() { if (db != null && db.isOpen()) db.close(); db = null; }

    public void close() { closeDatabase(); }

    private Comment map(Cursor c) {
        Comment cm = new Comment();
        cm.setId(c.getLong(c.getColumnIndexOrThrow("id")));
        cm.setUploaderId(c.getString(c.getColumnIndexOrThrow("user_id")));
        cm.setNoteId(c.getLong(c.getColumnIndexOrThrow("note_id")));
        cm.setContent(c.getString(c.getColumnIndexOrThrow("content")));
        cm.setCreatedAt(c.getString(c.getColumnIndexOrThrow("created_at")));
        return cm;
    }

    public List<Comment> listByNoteId(long noteId) {
        openDatabase();
        List<Comment> list = new ArrayList<>();
        try (Cursor c = db.query("T_Comment", null, "note_id=?", new String[]{String.valueOf(noteId)}, null, null, "created_at DESC")) {
            while (c != null && c.moveToNext()) list.add(map(c));
        }
        closeDatabase();
        return list;
    }

    public long add(String userId, long noteId, String content) {
        openDatabase();
        ContentValues cv = new ContentValues();
        cv.put("user_id", userId);
        cv.put("note_id", noteId);
        cv.put("content", content);
        long r = db.insert("T_Comment", null, cv);
        closeDatabase();
        return r;
    }

    public boolean delete(long id, String userId) {
        openDatabase();
        int rows = db.delete("T_Comment", "id=? AND user_id=?", new String[]{String.valueOf(id), userId});
        closeDatabase();
        return rows > 0;
    }
}