-- Migration 198: GlobalConnect extraction context + richer IPAM relations

ALTER TABLE extraction_lines
ADD COLUMN IF NOT EXISTS provider_reference VARCHAR(100),
ADD COLUMN IF NOT EXISTS customer_reference VARCHAR(100),
ADD COLUMN IF NOT EXISTS circuit_id VARCHAR(100),
ADD COLUMN IF NOT EXISTS end_customer_name VARCHAR(255),
ADD COLUMN IF NOT EXISTS period_start DATE,
ADD COLUMN IF NOT EXISTS period_end DATE,
ADD COLUMN IF NOT EXISTS service_address TEXT;

CREATE INDEX IF NOT EXISTS idx_extraction_lines_provider_reference ON extraction_lines(provider_reference);
CREATE INDEX IF NOT EXISTS idx_extraction_lines_circuit_id ON extraction_lines(circuit_id);
CREATE INDEX IF NOT EXISTS idx_extraction_lines_end_customer_name ON extraction_lines(end_customer_name);

COMMENT ON COLUMN extraction_lines.provider_reference IS 'Provider reference from invoice context (e.g. DSL-EB722388, NKA020902)';
COMMENT ON COLUMN extraction_lines.customer_reference IS 'Customer account/reference from supplier invoice';
COMMENT ON COLUMN extraction_lines.circuit_id IS 'Circuit or service identifier for the billed line';
COMMENT ON COLUMN extraction_lines.end_customer_name IS 'Named end customer from invoice context';
COMMENT ON COLUMN extraction_lines.period_start IS 'Billing period start date for the extracted line';
COMMENT ON COLUMN extraction_lines.period_end IS 'Billing period end date for the extracted line';
COMMENT ON COLUMN extraction_lines.service_address IS 'Full service address captured from invoice context';

ALTER TABLE internet_connections_ip_ranges
ADD COLUMN IF NOT EXISTS provider_reference VARCHAR(100),
ADD COLUMN IF NOT EXISTS contract_number VARCHAR(100),
ADD COLUMN IF NOT EXISTS customer_id INTEGER REFERENCES customers(id) ON DELETE SET NULL,
ADD COLUMN IF NOT EXISTS service_address VARCHAR(500),
ADD COLUMN IF NOT EXISTS monthly_cost NUMERIC(12,2) DEFAULT 0,
ADD COLUMN IF NOT EXISTS sales_price NUMERIC(12,2) DEFAULT 0;

CREATE INDEX IF NOT EXISTS idx_internet_connections_ip_ranges_customer_id
ON internet_connections_ip_ranges(customer_id);

ALTER TABLE internet_connections_ip_addresses
ADD COLUMN IF NOT EXISTS assigned_customer_id INTEGER REFERENCES customers(id) ON DELETE SET NULL,
ADD COLUMN IF NOT EXISTS assigned_connection_id INTEGER REFERENCES internet_connections_connections(id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS idx_internet_connections_ip_addresses_assigned_customer_id
ON internet_connections_ip_addresses(assigned_customer_id);

CREATE INDEX IF NOT EXISTS idx_internet_connections_ip_addresses_assigned_connection_id
ON internet_connections_ip_addresses(assigned_connection_id);
