-- ============================================================================
-- Add project_id column to meters table
-- This establishes the relationship between meters and projects
-- ============================================================================

-- Step 1: Add the column as nullable first (to allow existing data)
ALTER TABLE meters 
ADD COLUMN IF NOT EXISTS project_id UUID;

-- Step 2: For existing meters without project_id, try to get it from their concentrator
UPDATE meters m
SET project_id = c.project_id
FROM concentrators c
WHERE m.concentrator_id = c.id
  AND m.project_id IS NULL
  AND m.concentrator_id IS NOT NULL;

-- Step 3: Add foreign key constraint
ALTER TABLE meters
DROP CONSTRAINT IF EXISTS meters_project_id_fkey;

ALTER TABLE meters 
ADD CONSTRAINT meters_project_id_fkey 
FOREIGN KEY (project_id) 
REFERENCES projects(id) 
ON DELETE CASCADE;

-- Step 4: Create index for better query performance
CREATE INDEX IF NOT EXISTS idx_meters_project_id ON meters(project_id);

-- Step 5: Add comment for documentation
COMMENT ON COLUMN meters.project_id IS 'Project to which this meter belongs';

-- ============================================================================
-- Verify the changes
-- ============================================================================

-- Check if the column was added
SELECT 
    column_name, 
    data_type, 
    is_nullable,
    column_default
FROM information_schema.columns 
WHERE table_name = 'meters' 
  AND column_name = 'project_id';

-- Check the constraint
SELECT
    conname AS constraint_name,
    contype AS constraint_type,
    pg_get_constraintdef(oid) AS constraint_definition
FROM pg_constraint
WHERE conrelid = 'meters'::regclass
  AND conname LIKE '%project_id%';

-- Show meters with their project info
SELECT 
    m.id,
    m.name,
    m.serial_number,
    m.project_id,
    p.name AS project_name,
    c.name AS concentrator_name
FROM meters m
LEFT JOIN projects p ON m.project_id = p.id
LEFT JOIN concentrators c ON m.concentrator_id = c.id
LIMIT 10;
