import fs from 'fs';
import express from 'express';
import session from 'express-session';
import passport from 'passport';
import './auth/google.js';
import uploadRoutes from './routes/upload.js';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';

import pool from './db.js';

await pool.query(`
  CREATE TABLE IF NOT EXISTS images (
    id SERIAL PRIMARY KEY,
    filename TEXT NOT NULL,
    title TEXT NOT NULL,
    description TEXT NOT NULL,
    uploader TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
  );
`);

dotenv.config();

const app = express();
const __dirname = path.dirname(fileURLToPath(import.meta.url));

app.use(session({ secret: "urlaubsgeheimnis", resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

function isLoggedIn(req, res, next) {
  req.user ? next() : res.redirect('/');
}

app.get('/', async (req, res) => {
  const result = await pool.query('SELECT * FROM images ORDER BY created_at DESC');
  const images = result.rows.map(img => ({
    id: img.id,
    title: img.title,
    description: img.description,
    path: `/uploads/${img.filename}`,
    uploader: img.uploader || 'Unbekannt'
  }));

  res.render('index', { user: req.user, images });
});

app.get('/auth/google',
  passport.authenticate('google', { scope: ['profile', 'email'] }));

app.get('/auth/google/callback',
  passport.authenticate('google', { failureRedirect: '/' }),
  (req, res) => {
    res.redirect('/');
  });

app.get('/logout', (req, res) => {
  req.logout(() => {
    res.redirect('/');
  });
});

app.get('/protected', isLoggedIn, (req, res) => {
  res.send(`Hallo ${req.user.displayName}, du bist eingeloggt!`);
});

app.use(express.urlencoded({ extended: true }));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.use(uploadRoutes);

app.listen(5000, () => {
  console.log("🚀 Server läuft auf http://localhost:5000");
});
