import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Product } from './entities/product.entity';

@Injectable()
export class ProductsService {
  constructor(
    @InjectRepository(Product)
    private readonly productRepository: Repository<Product>,
  ) {}

  async create(sellerId: string, data: Partial<Product>): Promise<Product> {
    const product = this.productRepository.create({
      sellerId,
      ...data,
      currency: 'USD',
    });
    return this.productRepository.save(product);
  }

  async findById(id: string): Promise<Product> {
    const product = await this.productRepository.findOne({ where: { id } });
    if (!product) throw new NotFoundException('Product not found');
    return product;
  }

  async findBySeller(sellerId: string): Promise<Product[]> {
    return this.productRepository.find({ 
      where: { sellerId, isActive: true },
      order: { createdAt: 'DESC' },
    });
  }

  async findByCategory(category: string, page = 1, limit = 20): Promise<[Product[], number]> {
    return this.productRepository.findAndCount({
      where: { category, isActive: true },
      skip: (page - 1) * limit,
      take: limit,
      order: { createdAt: 'DESC' },
    });
  }

  async update(id: string, sellerId: string, data: Partial<Product>): Promise<Product> {
    const product = await this.findById(id);
    if (product.sellerId !== sellerId) {
      throw new NotFoundException('Product not found');
    }
    await this.productRepository.update(id, data);
    return this.findById(id);
  }

  async setFlashPrice(id: string, sellerId: string, flashPrice: number, durationMinutes: number): Promise<Product> {
    const product = await this.findById(id);
    if (product.sellerId !== sellerId) {
      throw new NotFoundException('Product not found');
    }
    
    const expiresAt = new Date(Date.now() + durationMinutes * 60000);
    await this.productRepository.update(id, { flashPrice, flashExpiresAt: expiresAt });
    return this.findById(id);
  }

  async delete(id: string, sellerId: string): Promise<void> {
    const product = await this.findById(id);
    if (product.sellerId !== sellerId) {
      throw new NotFoundException('Product not found');
    }
    await this.productRepository.update(id, { isActive: false });
  }
}