import { Entity, Index, ManyToOne, Property, Enum, Unique } from '@mikro-orm/core';
import { BaseEntity } from '../../../common/entities/base.entity';
import { Restaurant } from '../../restaurants/entities/restaurant.entity';
import { normalizePhone } from '../../utils/phone.util';
import { CouponType } from '../interface/coupon';

@Entity({ tableName: 'coupons' })
@Unique({ properties: ['code', 'restaurant'] })
@Index({ properties: ['restaurant', 'code', 'isActive'] })
@Index({ properties: ['restaurant', 'isActive'] })
@Index({ properties: ['code'] })
export class Coupon extends BaseEntity {
  @ManyToOne(() => Restaurant)
  restaurant!: Restaurant;

  @Property()
  code!: string;

  @Property()
  name!: string;

  @Property({ type: 'text', nullable: true })
  description?: string;

  @Enum(() => CouponType)
  type!: CouponType;

  @Property({ type: 'decimal', precision: 10, scale: 2 })
  value!: number; // Discount amount or percentage

  @Property({ type: 'decimal', precision: 10, scale: 2, nullable: true })
  maxDiscount?: number; // Maximum discount for percentage coupons

  @Property({ type: 'decimal', precision: 10, scale: 2, nullable: true })
  minOrderAmount?: number; // Minimum order amount to use coupon

  @Property({ type: 'int', nullable: true })
  maxUses?: number; // Maximum number of times coupon can be used

  @Property({ type: 'int', default: 0 })
  usedCount: number = 0; // Number of times coupon has been used

  @Property({ type: 'int', nullable: true })
  maxUsesPerUser?: number; // Maximum uses per user

  @Property({ type: 'timestamptz', nullable: true })
  startDate?: Date; // Coupon validity start date

  @Property({ type: 'timestamptz', nullable: true })
  endDate?: Date; // Coupon validity end date

  @Property({ type: 'boolean', default: true })
  isActive: boolean = true;

  @Property({ type: 'json', nullable: true })
  foodCategories?: string[]; // Array of category IDs

  @Property({ type: 'json', nullable: true })
  foods?: string[]; // Array of food IDs

  private _userPhone?: string;

  @Property({ nullable: true })
  get userPhone(): string | undefined {
    return this._userPhone;
  }

  set userPhone(value: string | undefined) {
    this._userPhone = value ? normalizePhone(value) : undefined;
  }
}
