import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../common/prisma.service';
import { CreatePromotionDto } from './promos.dto';

@Injectable()
export class PromosService {
  constructor(private prisma: PrismaService) {}

  getActive() { return this.prisma.promotion.findMany({ where: { active: true, validUntil: { gte: new Date() } }, orderBy: { createdAt: 'desc' } }); }

  async validate(code: string) {
    const promo = await this.prisma.promotion.findUnique({ where: { code } });
    if (!promo || !promo.active || promo.validUntil < new Date()) return { applicable: false, message: 'Promo code invalid or expired' };
    return { code: promo.code, percentOff: promo.percentOff, amountOffMinor: promo.amountOffMinor, validUntil: promo.validUntil, applicable: true, message: promo.percentOff ? `${promo.percentOff}% off` : `ETB ${((promo.amountOffMinor ?? 0) / 100).toFixed(2)} off` };
  }

  create(dto: CreatePromotionDto) {
    return this.prisma.promotion.create({ data: { ...dto, validUntil: new Date(dto.validUntil) } });
  }
}
