-- Migration: Create mac_allocations table for MAC-based resource allocation
-- Purpose: MAC address binding for license and resource control
-- Date: 2026-04-27

-- Create mac_allocations table (simplified version for MVP)
CREATE TABLE IF NOT EXISTS mac_allocations (
    mac_address VARCHAR(17) PRIMARY KEY,
    machine_name VARCHAR(100),
    license_key VARCHAR(64),
    is_active BOOLEAN DEFAULT true,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Add comments
COMMENT ON TABLE mac_allocations IS 
'MAC address resource allocation: license binding and machine identification';

COMMENT ON COLUMN mac_allocations.mac_address IS 
'Network interface MAC address (format: a1:b2:c3:d4:e5:f6)';

COMMENT ON COLUMN mac_allocations.machine_name IS 
'Human-readable machine name (e.g., MacBook-Pro)';

COMMENT ON COLUMN mac_allocations.license_key IS 
'License key bound to this MAC address';

COMMENT ON COLUMN mac_allocations.is_active IS 
'Whether this MAC is currently active';

-- Create indexes
CREATE INDEX IF NOT EXISTS idx_mac_allocations_license 
ON mac_allocations(license_key);

CREATE INDEX IF NOT EXISTS idx_mac_allocations_active 
ON mac_allocations(is_active);

-- Insert default MAC allocation for current machine (placeholder)
-- Actual MAC address will be inserted during first registration
-- INSERT INTO mac_allocations (mac_address, machine_name, license_key, is_active)
-- VALUES ('<actual_mac>', 'MacBook-Pro', 'demo_license', true);

-- Update trigger for updated_at
CREATE OR REPLACE FUNCTION update_mac_allocations_updated_at()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trigger_mac_allocations_updated_at
BEFORE UPDATE ON mac_allocations
FOR EACH ROW
EXECUTE FUNCTION update_mac_allocations_updated_at();