import { Database } from "better-sqlite3";
import Location from "../entities/location";
import LocationsRepository from "../entities/locationsRepository";

export default class SqliteLocationsRepository implements LocationsRepository {
  constructor(private readonly db: Database) {}

  getAll(): Location[] {
    return this.db
      .prepare("SELECT id, name, lat, lon FROM locations")
      .all()
      .map((locationData) => {
        return Object.setPrototypeOf(locationData, Location);
      });
  }

  save(location: Location): void {
    this.db
      .prepare(
        "INSERT INTO locations (id, name, lat, lon) VALUES (@id, @name, @lat, @lon)"
      )
      .run({
        id: location.id,
        name: location.name,
        lat: location.lat,
        lon: location.lon,
      });
  }
}
