import { sql } from 'drizzle-orm'
import type { Querier } from '@platform-modules/db'
import type { CartSchema } from './schema.js'

export class CartMigrateError extends Error {
  override readonly name = 'CartMigrateError'
  readonly code = 'CART_MIGRATE' as const

  constructor(readonly detail: string) {
    super(`cart migrate: ${detail}`)
  }
}

export function isCartMigrateError(e: unknown): e is CartMigrateError {
  return (
    typeof e === 'object' &&
    e !== null &&
    (e as { name?: unknown }).name === 'CartMigrateError' &&
    (e as { code?: unknown }).code === 'CART_MIGRATE'
  )
}

const MIGRATION_STATEMENTS = [
  sql`
    CREATE TABLE IF NOT EXISTS cart (
      id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
      currency text NOT NULL,
      user_id text,
      created_at timestamptz(3) NOT NULL DEFAULT NOW(),
      updated_at timestamptz(3) NOT NULL DEFAULT NOW()
    )
  `,
  sql`
    CREATE TABLE IF NOT EXISTS cart_line (
      id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
      cart_id uuid NOT NULL,
      variant_id uuid NOT NULL,
      qty integer NOT NULL,
      amount bigint NOT NULL,
      currency text NOT NULL,
      price_mode text NOT NULL,
      vendor_id text
    )
  `,
]

export async function pushSchema(db: Querier<CartSchema>): Promise<void> {
  try {
    for (const statement of MIGRATION_STATEMENTS) {
      await db.execute(statement)
    }
  } catch (e) {
    throw new CartMigrateError(e instanceof Error ? e.message : String(e))
  }
}
