-- Migration: 073_locations_customer_relation
-- Created: 2026-01-31
-- Description: Add customer relation to locations and customer_site type

BEGIN;

ALTER TABLE locations_locations
    ADD COLUMN IF NOT EXISTS customer_id INTEGER;

ALTER TABLE locations_locations
    DROP CONSTRAINT IF EXISTS locations_locations_customer_id_fkey;

ALTER TABLE locations_locations
    ADD CONSTRAINT locations_locations_customer_id_fkey
    FOREIGN KEY (customer_id)
    REFERENCES customers(id)
    ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS idx_locations_customer_id
    ON locations_locations(customer_id);

ALTER TABLE locations_locations
    DROP CONSTRAINT IF EXISTS locations_locations_location_type_check;

ALTER TABLE locations_locations
    ADD CONSTRAINT locations_locations_location_type_check
    CHECK (location_type IN (
        'bygning',
        'etage',
        'rum',
        'vehicle',
        'branch',
        'warehouse',
        'service_center',
        'client_site',
        'customer_site'
    ));

COMMIT;
