const express = require('express');
const cors = require('cors');
const SourceAdapter = require('./SourceAdapter');
require('dotenv').config();

const app = express();
const PORT = process.env.PORT || 3000;

app.use(cors());
app.use(express.json());

app.get('/api/home', async (req, res) => {
  try {
    const sections = await SourceAdapter.getHomeSections();
    res.json(sections);
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch home sections', details: err.message });
  }
});

app.get('/api/trending', async (req, res) => {
  try {
    const trending = await SourceAdapter.getTrending();
    res.json(trending);
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch trending', details: err.message });
  }
});

app.get('/api/top10', async (req, res) => {
  try {
    const top10 = await SourceAdapter.getTop10();
    res.json(top10);
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch top 10', details: err.message });
  }
});

app.get('/api/movies/popular', async (req, res) => {
  try {
    const page = req.query.page || 1;
    const movies = await SourceAdapter.getPopularMovies(page);
    res.json(movies);
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch popular movies', details: err.message });
  }
});

app.get('/api/tv/popular', async (req, res) => {
  try {
    const page = req.query.page || 1;
    const tv = await SourceAdapter.getPopularTV(page);
    res.json(tv);
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch popular tv shows', details: err.message });
  }
});

app.get('/api/search', async (req, res) => {
  try {
    const { q, page } = req.query;
    const results = await SourceAdapter.searchTitles(q, page);
    res.json(results);
  } catch (err) {
    res.status(500).json({ error: 'Failed to search titles', details: err.message });
  }
});

app.get('/api/movie/:id', async (req, res) => {
  try {
    const movie = await SourceAdapter.getMovie(req.params.id);
    res.json(movie);
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch movie details', details: err.message });
  }
});

app.get('/api/tv/:id', async (req, res) => {
  try {
    const tv = await SourceAdapter.getTVShow(req.params.id);
    res.json(tv);
  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch TV details', details: err.message });
  }
});

app.listen(PORT, () => {
  console.log('Backend API running on http://localhost:' + PORT);
});
