import 'package:http/http.dart' as http;
import 'dart:convert';
import 'platform_service.dart';
import '../models/product.dart';

class SquareService implements PlatformService {
  final String accessToken;
  final String locationId; // Optional but good for scoped inventory
  
  // Prod: https://connect.squareup.com/v2
  // Sandbox: https://connect.squareupsandbox.com/v2
  // For now assuming PROD or user configurable base URL handled elsewhere? 
  // Let's stick to Prod for now, or allow base URL injection.
  final String baseUrl = 'https://connect.squareup.com/v2';

  SquareService({required this.accessToken, required this.locationId});
  
  Map<String, String> get _headers => {
    'Authorization': 'Bearer $accessToken',
    'Content-Type': 'application/json',
    'Square-Version': '2023-10-20', // Pin a recent version
  };

  @override
  Future<List<Product>> fetchProducts({int page = 1, String search = ''}) async {
    // Square 'List Catalog' endpoint
    // https://developer.squareup.com/reference/square/catalog-api/list-catalog
    // types=ITEM
    
    // Note: Square uses cursor-based pagination, not page numbers.
    // Simplifying mapping: Page 1 = fresh call. Future pages not easily supported without cursor tracking in state.
    // For this POC, we'll fetch the first batch.
    
    final uri = Uri.parse('$baseUrl/catalog/list').replace(queryParameters: {
        'types': 'ITEM',
    });

    final response = await http.get(uri, headers: _headers);

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      // Map Square Items to a generic structure or return raw?
      // PlatformService returns List<dynamic>, usually expecting a list of product objects.
      // Square returns { "objects": [...] }
      // return data['objects'] ?? [];
      return []; // Return empty list for now until mapping is implemented
    } else {
      throw Exception('Failed to fetch Square products: ${response.statusCode} ${response.body}');
    }
  }

  @override
  Future<Product> fetchProduct(int id) async {
     // Square IDs are strings (e.g. "C75..."). The interface uses int id.
     // This is a mismatch in our PlatformService design!
     // We need to update PlatformService to use dynamic or String for IDs.
     throw UnimplementedError('Square IDs are strings, refactor pending.');
  }

  @override
  Future<Product> updateProduct(int id, Map<String, dynamic> data) async {
      // Interface mismatch again.
      throw UnimplementedError();
  }

  @override
  Future<dynamic> deleteProduct(int id) async {
      throw UnimplementedError();
  }
}
