const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const escapeStringRegex  = require('escape-string-regexp');

const Post = require("./models/post");

const app = express();

mongoose
  .connect( "mongodb+srv://student-242:CPT242-ATC@cluster0-a5gak.mongodb.net/video" )
  // .connect( "mongodb+srv://viewUser:zxcASD123@cluster0.9j1th.mongodb.net/video" )
  .then(() => { console.log("Connected to database!"); })
  .catch(() => { console.log("Connection failed!"); });

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use((req, res, next) => { res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept" );
  res.setHeader( "Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS" );
  next();
});

app.get("/api/posts", (req, res, next) => {
  Post.find()
    .then(documents => {
    res.status(200).json({
      message: "Posts fetched successfully!",
      posts: documents
    });
  });
});


module.exports = app;
