import { AppDataSource } from '../config/database';
import { ShopProduct, ShopProductCategory, ShopProductStatus } from '../models/ShopProduct';

export class ShopService {
  // ─── Public ─────────────────────────────────────────────────

  static async getProducts(
    category?: string,
    search?: string,
    page: number = 1,
    limit: number = 20,
  ) {
    const repo = AppDataSource.getRepository(ShopProduct);
    const qb = repo.createQueryBuilder('product')
      .where('product.status = :status', { status: 'en_vente' })
      .orderBy('product.created_at', 'DESC');

    if (category) {
      qb.andWhere('product.category = :category', { category });
    }

    if (search) {
      qb.andWhere(
        '(product.name ILIKE :search OR product.description ILIKE :search)',
        { search: `%${search}%` },
      );
    }

    const skip = (page - 1) * limit;
    qb.skip(skip).take(limit);

    const [products, total] = await qb.getManyAndCount();

    return {
      products,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  static async getProduct(id: string) {
    const repo = AppDataSource.getRepository(ShopProduct);
    const product = await repo.findOne({
      where: { id, status: 'en_vente' },
    });
    return product ?? null;
  }

  // ─── Admin ───────────────────────────────────────────────────

  static async getAllProducts(
    category?: string,
    search?: string,
    status?: string,
    page: number = 1,
    limit: number = 20,
  ) {
    const repo = AppDataSource.getRepository(ShopProduct);
    const qb = repo.createQueryBuilder('product')
      .orderBy('product.created_at', 'DESC');

    if (category) {
      qb.andWhere('product.category = :category', { category });
    }

    if (search) {
      qb.andWhere(
        '(product.name ILIKE :search OR product.description ILIKE :search)',
        { search: `%${search}%` },
      );
    }

    if (status) {
      qb.andWhere('product.status = :status', { status });
    }

    const skip = (page - 1) * limit;
    qb.skip(skip).take(limit);

    const [products, total] = await qb.getManyAndCount();

    return {
      products,
      total,
      page,
      limit,
      totalPages: Math.ceil(total / limit),
    };
  }

  static async getStats() {
    const repo = AppDataSource.getRepository(ShopProduct);

    const [totalProducts, outOfStockCount] = await Promise.all([
      repo.count({ where: { status: 'en_vente' } }),
      repo.count({ where: { status: 'epuise' } }),
    ]);

    return {
      totalProducts,
      outOfStockCount,
      sales24h: 0,       // placeholder — requires a future purchase/transaction model
      revenue24h: 0,     // placeholder — requires a future purchase/transaction model
    };
  }

  static async createProduct(data: {
    name: string;
    description: string;
    price: number;
    category: ShopProductCategory;
    stock?: number;
    image_url?: string;
    status?: ShopProductStatus;
  }) {
    const repo = AppDataSource.getRepository(ShopProduct);

    const product = repo.create({
      name: data.name,
      description: data.description,
      price: data.price,
      category: data.category,
      stock: data.stock ?? 0,
      image_url: data.image_url ?? null,
      status: data.status ?? 'en_vente',
    });

    await repo.save(product);
    return product;
  }

  static async updateProduct(
    id: string,
    data: Partial<{
      name: string;
      description: string;
      price: number;
      category: ShopProductCategory;
      stock: number;
      image_url: string;
      status: ShopProductStatus;
    }>,
  ) {
    const repo = AppDataSource.getRepository(ShopProduct);
    const product = await repo.findOne({ where: { id } });

    if (!product) {
      throw new Error('Produit introuvable');
    }

    if (data.name !== undefined) product.name = data.name;
    if (data.description !== undefined) product.description = data.description;
    if (data.price !== undefined) product.price = data.price;
    if (data.category !== undefined) product.category = data.category;
    if (data.stock !== undefined) product.stock = data.stock;
    if (data.image_url !== undefined) product.image_url = data.image_url;
    if (data.status !== undefined) product.status = data.status;

    await repo.save(product);
    return product;
  }

  static async deleteProduct(id: string) {
    const repo = AppDataSource.getRepository(ShopProduct);
    const product = await repo.findOne({ where: { id } });

    if (!product) {
      throw new Error('Produit introuvable');
    }

    // Soft delete — set status to 'desactive'
    product.status = 'desactive';
    await repo.save(product);
    return { id, desactive: true };
  }
}
