import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
} from 'typeorm';

export type SubStatus =
  | 'incomplete'
  | 'active'
  | 'past_due'
  | 'canceled'
  | 'expired';

/**
 * One row per company. Tracks the Stripe subscription/payment (or a superadmin
 * comp) that unlocks the client portal for that company. Connection: scheme_dbs.
 *
 * plan values:
 *   'portal_access' -> normal paid (Stripe)
 *   'comp'          -> free access granted by a superadmin (no charge)
 *   'manual'        -> marked paid by admin (offline / bank transfer)
 */
@Entity('client_subscriptions')
@Index(['company_id'], { unique: true })
@Index(['status'])
export class ClientSubscription {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  company_id: number;

  @Column({ type: 'int', nullable: true })
  client_user_id: number | null;

  @Column({ type: 'varchar', length: 255, nullable: true })
  stripe_customer_id: string | null;

  @Column({ type: 'varchar', length: 255, nullable: true })
  stripe_subscription_id: string | null;

  @Column({ type: 'varchar', length: 255, nullable: true })
  stripe_checkout_session_id: string | null;

  @Column({ type: 'varchar', length: 100, default: 'portal_access' })
  plan: string;

  /**
   * Superadmin paywall switch for THIS company.
   *   false (default) → portal works normally, NO gateway shown.
   *   true            → gated: the client must be active (paid/comp/manual)
   *                     to enter the dashboard or app, otherwise they see
   *                     the payment gateway. This is the per-company enable.
   */
  @Column({ type: 'boolean', default: false })
  billing_enabled: boolean;

  @Column({
    type: 'enum',
    enum: ['incomplete', 'active', 'past_due', 'canceled', 'expired'],
    default: 'incomplete',
  })
  status: SubStatus;

  /** amount actually charged (minor units), filled from Stripe */
  @Column({ type: 'int', nullable: true })
  amount: number | null;

  @Column({ type: 'varchar', length: 10, default: 'aed' })
  currency: string;

  // -- Admin-set price for THIS company (dynamic) ----------------
  /** what the admin wants this company to pay (minor units). null = use global default */
  @Column({ type: 'int', nullable: true })
  price_amount: number | null;

  @Column({ type: 'varchar', length: 10, nullable: true })
  price_currency: string | null;

  /** 'year' | 'month' | 'one_time' */
  @Column({ type: 'varchar', length: 20, nullable: true })
  price_interval: string | null;
  // --------------------------------------------------------------

  /** NULL = lifetime (one-time payment or a comp) */
  @Column({ type: 'datetime', nullable: true })
  current_period_end: Date | null;

  @CreateDateColumn()
  created_at: Date;

  @UpdateDateColumn()
  updated_at: Date;
}
