import db from "../connections/sqlite";
import { ObjectId } from "mongodb";
import { IThumbnailDB } from "../dbTypes";

const rowToThumbnail = (row: any) => {
  if (!row) return null;

  return {
    _id: row.id,
    name: row.name,
    owner: row.owner,
    data: row.data || undefined,
    path: row.path || undefined,
    IV: row.iv || undefined,
    s3ID: row.s3ID || undefined,
    personalFile: row.personalFile ? true : undefined,
    createdAt: new Date(row.createdAt),
    updatedAt: new Date(row.updatedAt),
  };
};

class ThumbnailDB implements IThumbnailDB {
  constructor() {}

  // READ

  getThumbnailInfo = async (userID: string, thumbnailID: string) => {
    const row = db
      .prepare("SELECT * FROM thumbnails WHERE id = ? AND owner = ?")
      .get(thumbnailID, userID);
    return rowToThumbnail(row);
  };

  // DELETE

  removeThumbnail = async (userID: string, thumbnailID: any) => {
    const result = db
      .prepare("DELETE FROM thumbnails WHERE id = ? AND owner = ?")
      .run(thumbnailID.toString(), userID);
    return result;
  };

  // CREATE

  createThumbnail = async (data: {
    name: string;
    owner: string;
    IV: Buffer;
    path?: string;
    s3ID?: string;
  }) => {
    const id = new ObjectId().toString();
    const now = new Date().toISOString();

    db.prepare(
      `INSERT INTO thumbnails (id, name, owner, data, path, iv, s3ID, personalFile, createdAt, updatedAt)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
    ).run(
      id,
      data.name,
      data.owner,
      null,
      data.path || null,
      data.IV,
      data.s3ID || null,
      0,
      now,
      now
    );

    const row = db.prepare("SELECT * FROM thumbnails WHERE id = ?").get(id);
    return rowToThumbnail(row);
  };
}

export default ThumbnailDB;
