import {
  pgTable,
  text,
  integer,
  timestamp,
  jsonb,
  boolean
} from 'drizzle-orm/pg-core'
import { customers } from './customers'
import { prices } from './prices'
import { user } from './auth'
import { relations } from 'drizzle-orm'

export const subscriptions = pgTable('subscriptions', {
  id: text('id').primaryKey(), // Stripe Subscription ID
  customerId: text('customer_id').references(() => customers.id, { onDelete: 'cascade' }), // Stripe Customer ID
  priceId: text('price_id').references(() => prices.id), // Stripe Price ID
  userId: text('user_id').references(() => user.id, { onDelete: 'cascade' }),
  status: text('status').notNull(),
  metadata: jsonb('metadata'),
  quantity: integer('quantity').notNull(),
  cancelAtPeriodEnd: boolean('cancel_at_period_end').notNull(),
  currentPeriodEnd: timestamp('current_period_end'),
  currentPeriodStart: timestamp('current_period_start'),
  endedAt: timestamp('ended_at'),
  cancelAt: timestamp('cancel_at'),
  trialStart: timestamp('trial_start'),
  trialEnd: timestamp('trial_end'),
  createdAt: timestamp('created_at').defaultNow(),
  updatedAt: timestamp('updated_at').defaultNow()
})

export const subscriptionsRelations = relations(subscriptions, ({ one }) => ({
  customer: one(customers, {
    fields: [subscriptions.customerId],
    references: [customers.id]
  }),
  price: one(prices, {
    fields: [subscriptions.priceId],
    references: [prices.id]
  }),
  user: one(user, {
    fields: [subscriptions.userId],
    references: [user.id]
  })
}))
