CREATE TABLE IF NOT EXISTS locations_cross_fields (
    id SERIAL PRIMARY KEY,
    location_id INTEGER NOT NULL REFERENCES locations_locations(id) ON DELETE CASCADE,
    name VARCHAR(100) NOT NULL,
    port_count INTEGER NOT NULL CHECK (port_count BETWEEN 1 AND 999),
    notes TEXT,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
    deleted_at TIMESTAMP
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_cross_fields_location_name_active
    ON locations_cross_fields(location_id, lower(name)) WHERE deleted_at IS NULL;

CREATE TABLE IF NOT EXISTS locations_cross_field_ports (
    id SERIAL PRIMARY KEY,
    cross_field_id INTEGER NOT NULL REFERENCES locations_cross_fields(id) ON DELETE CASCADE,
    port_number INTEGER NOT NULL CHECK (port_number > 0),
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    UNIQUE(cross_field_id, port_number)
);

CREATE INDEX IF NOT EXISTS idx_cross_field_ports_field ON locations_cross_field_ports(cross_field_id);
