import 'dotenv/config';
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import { db } from './lib/db.js';
import { authRouter } from './routes/auth.js';
import { usersRouter } from './routes/users.js';
import { partnersRouter } from './routes/partners.js';
import { playlistsRouter } from './routes/playlists.js';
import { syncUserData, captureNowPlaying } from './lib/sync.js';

const app = express();

app.use(helmet());
app.use(cors({ origin: [
  'http://localhost:3000',
  'https://159.195.9.107:3443'
], credentials: true }));
app.use(express.json({ limit: '1mb' }));
app.use(express.urlencoded({ extended: false }));
app.use(morgan('dev'));

// Initialize DB
db.initialize();

app.get('/health', (_req, res) => {
  res.json({ ok: true });
});

app.use('/auth', authRouter);
app.use('/users', usersRouter);
app.use('/partners', partnersRouter);
app.use('/playlists', playlistsRouter);

const PORT = process.env.PORT ? Number(process.env.PORT) : 8080;
app.listen(PORT, () => {
  console.log(`API server listening on http://0.0.0.0:${PORT}`);
});

// Periodic refreshes
const REFRESH_INTERVAL_MS = 2 * 60 * 1000; // full sync
const NOWPLAYING_INTERVAL_MS = 20 * 1000; // capture now playing
setInterval(() => {
  try {
    const users = db.db.prepare('SELECT id FROM users').all() as Array<{ id: string }>;
    for (const u of users) {
      syncUserData(u.id).catch(() => void 0);
    }
  } catch (e) {
    // ignore timer errors
  }
}, REFRESH_INTERVAL_MS);

setInterval(() => {
  try {
    const users = db.db.prepare('SELECT id FROM users').all() as Array<{ id: string }>;
    for (const u of users) captureNowPlaying(u.id).catch(() => void 0);
  } catch {}
}, NOWPLAYING_INTERVAL_MS);


