import 'package:postgres/postgres.dart';
import '../models/movie.dart';
import 'local_storage_service.dart';

class DatabaseService {
  static const String host = 'localhost';
  static const String database = 'flutterBDD';
  static const String username = 'postgres';
  static const String password = 'root';
  static const int port = 5432;

  static Connection? _connection;
  static bool _useLocalStorage = false;

  static Future<Connection> get connection async {
    if (_connection == null && !_useLocalStorage) {
      try {
        _connection = await Connection.open(
          Endpoint(
            host: host,
            port: port,
            database: database,
            username: username,
            password: password,
          ),
        );
        await _createTables();
      } catch (e) {
        print('Erreur de connexion à PostgreSQL: $e');
        print('Utilisation du stockage local à la place...');
        _useLocalStorage = true;
        throw Exception('PostgreSQL non disponible, utilisation du stockage local');
      }
    }
    if (_useLocalStorage) {
      throw Exception('Utilisation du stockage local');
    }
    return _connection!;
  }

  static Future<void> _createTables() async {
    final conn = await connection;
    
    await conn.execute('''
      CREATE TABLE IF NOT EXISTS favorites (
        id SERIAL PRIMARY KEY,
        movie_id INTEGER NOT NULL,
        title TEXT NOT NULL,
        description TEXT,
        image_url TEXT,
        category TEXT,
        director TEXT,
        release_date TEXT,
        rating REAL,
        original_title TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      )
    ''');
  }

  static Future<bool> addToFavorites(Movie movie) async {
    try {
      final conn = await connection;
      
      final existing = await conn.execute(
        Sql.named('SELECT id FROM favorites WHERE movie_id = @movieId'),
        parameters: {'movieId': movie.id},
      );
      
      if (existing.isNotEmpty) {
        return false;
      }
      
      await conn.execute(
        Sql.named('''
          INSERT INTO favorites (
            movie_id, title, description, image_url, category, 
            director, release_date, rating, original_title
          ) VALUES (
            @movieId, @title, @description, @imageUrl, @category,
            @director, @releaseDate, @rating, @originalTitle
          )
        '''),
        parameters: {
          'movieId': movie.id,
          'title': movie.title,
          'description': movie.description,
          'imageUrl': movie.imageUrl,
          'category': movie.category,
          'director': movie.director,
          'releaseDate': movie.releaseDate,
          'rating': movie.rating,
          'originalTitle': movie.originalTitle,
        },
      );
      
      return true;
    } catch (e) {
      print('Erreur PostgreSQL, utilisation du stockage local: $e');
      return await LocalStorageService.addToFavorites(movie);
    }
  }

  static Future<bool> removeFromFavorites(int movieId) async {
    try {
      final conn = await connection;
      
      final result = await conn.execute(
        Sql.named('DELETE FROM favorites WHERE movie_id = @movieId'),
        parameters: {'movieId': movieId},
      );
      
      return result.length > 0;
    } catch (e) {
      print('Erreur PostgreSQL, utilisation du stockage local: $e');
      return await LocalStorageService.removeFromFavorites(movieId);
    }
  }

  static Future<bool> isFavorite(int movieId) async {
    try {
      final conn = await connection;
      
      final result = await conn.execute(
        Sql.named('SELECT id FROM favorites WHERE movie_id = @movieId'),
        parameters: {'movieId': movieId},
      );
      
      return result.isNotEmpty;
    } catch (e) {
      print('Erreur PostgreSQL, utilisation du stockage local: $e');
      return await LocalStorageService.isFavorite(movieId);
    }
  }

  static Future<List<Movie>> getFavorites() async {
    try {
      final conn = await connection;
      
      final results = await conn.execute(
        Sql('SELECT * FROM favorites ORDER BY created_at DESC'),
      );
      
      return results.map((row) => Movie(
        id: row[1] as int,
        title: row[2] as String,
        description: row[3] as String,
        imageUrl: row[4] as String,
        category: row[5] as String,
        director: row[6] as String,
        releaseDate: row[7] as String,
        rating: (row[8] as double?) ?? 0.0,
        originalTitle: row[9] as String,
        isFeatured: false,
      )).toList();
    } catch (e) {
      print('Erreur PostgreSQL, utilisation du stockage local: $e');
      return await LocalStorageService.getFavorites();
    }
  }

  static Future<void> close() async {
    if (_connection != null) {
      await _connection!.close();
      _connection = null;
    }
  }
}
