-- Migration: Create import_sessions table
-- Run this against your PostgreSQL database

CREATE TABLE IF NOT EXISTS import_sessions (
  id SERIAL PRIMARY KEY,
  user_id INTEGER NOT NULL,
  name VARCHAR(255),                    -- NULL for unnamed/autosave sessions
  current_step VARCHAR(50) NOT NULL,    -- 'validation' | 'imageUpload'
  data JSONB NOT NULL,                  -- Product rows
  product_images JSONB,                 -- Image assignments
  global_selections JSONB,              -- Supplier, company, line, subline
  validation_state JSONB,               -- Errors, UPC status, generated item numbers
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
);

-- Ensure only one unnamed session per user (autosave slot)
CREATE UNIQUE INDEX IF NOT EXISTS idx_unnamed_session_per_user
  ON import_sessions (user_id)
  WHERE name IS NULL;

-- Index for fast user lookups
CREATE INDEX IF NOT EXISTS idx_import_sessions_user_id
  ON import_sessions (user_id);

-- Add comment for documentation
COMMENT ON TABLE import_sessions IS 'Stores in-progress product import sessions for users';
COMMENT ON COLUMN import_sessions.name IS 'Session name - NULL indicates the single unnamed/autosave session per user';
COMMENT ON COLUMN import_sessions.current_step IS 'Which step the user was on: validation or imageUpload';
