const low = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const path = require('path');

const adapter = new FileSync(path.join(__dirname, 'db.json'));
const db = low(adapter);

// default structure
db.defaults({ rooms: [], messages: [], lastRoomId: 100 }).write();

function createRoom({ user, site, email }) {
  const id = db.get('lastRoomId').value() + 1;
  db.set('lastRoomId', id).write();

  const now = new Date().toISOString();
  const room = {
    id,
    user,
    email: email || '',
    site,
    status: 'open', // 'open' | 'closed'
    blocked: false,
    created_at: now,
    last_activity: now,
  };
  db.get('rooms').push(room).write();
  return room;
}

function getRoom(id) {
  return db.get('rooms').find({ id: Number(id) }).value();
}

function getOpenRooms() {
  return db.get('rooms').filter({ status: 'open' }).value();
}

function touchActivity(room_id) {
  db.get('rooms')
    .find({ id: Number(room_id) })
    .assign({ last_activity: new Date().toISOString() })
    .write();
}

function setRoomStatus(room_id, status) {
  return db.get('rooms').find({ id: Number(room_id) }).assign({ status }).write();
}

function setRoomBlocked(room_id, blocked) {
  return db.get('rooms').find({ id: Number(room_id) }).assign({ blocked }).write();
}

function addMessage({ room_id, from, text, type = 'text', url = null, filename = null }) {
  const msg = {
    room_id: Number(room_id),
    from, // 'user' | 'admin'
    text,
    type, // 'text' | 'image' | 'file'
    url, // path publik ke file, ex: /uploads/xxx.jpg
    filename,
    ts: new Date().toISOString(),
  };
  db.get('messages').push(msg).write();
  return msg;
}

function getMessages(room_id) {
  return db.get('messages').filter({ room_id: Number(room_id) }).value();
}

module.exports = {
  db,
  createRoom,
  getRoom,
  getOpenRooms,
  touchActivity,
  setRoomStatus,
  setRoomBlocked,
  addMessage,
  getMessages,
};
