-- Migration 023: IACE Production Lines
-- Adds tables for chaining multiple IACE projects into a production line
-- dashboard view, where each station maps to an existing IACE project.

-- ============================================================================
-- 1. Production lines (top-level grouping entity)
-- ============================================================================

CREATE TABLE IF NOT EXISTS iace_production_lines (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL,
    name TEXT NOT NULL DEFAULT '',
    description TEXT DEFAULT '',
    layout JSONB DEFAULT '{}',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_iace_pl_tenant ON iace_production_lines(tenant_id);

-- ============================================================================
-- 2. Production line stations (link table: line <-> project)
-- ============================================================================

CREATE TABLE IF NOT EXISTS iace_production_line_stations (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    line_id UUID NOT NULL REFERENCES iace_production_lines(id) ON DELETE CASCADE,
    project_id UUID NOT NULL REFERENCES iace_projects(id) ON DELETE CASCADE,
    station_type TEXT NOT NULL DEFAULT 'assembly',
    station_label TEXT DEFAULT '',
    sort_order INT DEFAULT 0,
    position_x FLOAT DEFAULT 0,
    position_y FLOAT DEFAULT 0,
    metadata JSONB DEFAULT '{}',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_pls_line ON iace_production_line_stations(line_id);
