package com.example.myapplication.repository;

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

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

    public LikeRepository(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 boolean addLike(String userId, long noteId) {
        openDatabase();
        boolean ok = false;
        db.beginTransaction();
        try {
            ContentValues cv = new ContentValues();
            cv.put("user_id", userId);
            cv.put("note_id", noteId);
            long r = db.insertWithOnConflict("T_Like", null, cv, SQLiteDatabase.CONFLICT_IGNORE);
            if (r != -1) {
                db.execSQL("UPDATE T_Note SET like_count = COALESCE(like_count,0) + 1 WHERE id=?", new Object[]{noteId});
                ok = true;
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
        closeDatabase();
        return ok;
    }

    public boolean removeLike(String userId, long noteId) {
        openDatabase();
        boolean ok = false;
        db.beginTransaction();
        try {
            int rows = db.delete("T_Like", "user_id=? AND note_id=?", new String[]{userId, String.valueOf(noteId)});
            if (rows > 0) {
                db.execSQL("UPDATE T_Note SET like_count = CASE WHEN COALESCE(like_count,0) > 0 THEN like_count - 1 ELSE 0 END WHERE id=?", new Object[]{noteId});
                ok = true;
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
        closeDatabase();
        return ok;
    }

    public boolean checkUserLikeStatus(String userId, long noteId) {
        openDatabase();
        boolean exists = false;
        try (Cursor c = db.query("T_Like", new String[]{"user_id"}, "user_id=? AND note_id=?",
                new String[]{userId, String.valueOf(noteId)}, null, null, null)) {
            exists = c != null && c.moveToFirst();
        }
        closeDatabase();
        return exists;
    }

    public int getLikeCount(long noteId) {
        openDatabase();
        int count = 0;
        try (Cursor c = db.rawQuery("SELECT COUNT(*) FROM T_Like WHERE note_id=?", new String[]{String.valueOf(noteId)})) {
            if (c != null && c.moveToFirst()) count = c.getInt(0);
        }
        closeDatabase();
        return count;
    }
}