-- Migration: Create user_companies pivot table
-- Description: N:M relationship for multi-tenant - users can belong to multiple companies

CREATE TABLE IF NOT EXISTS user_companies (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v7(),
    user_id UUID NOT NULL,
    company_id UUID NOT NULL,
    role VARCHAR(20) NOT NULL CHECK (role IN ('admin', 'recruiter')),
    permissions JSONB,  -- Optional granular permissions
    
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    
    -- Foreign keys
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (company_id) REFERENCES companies(id) ON DELETE CASCADE,
    
    -- Ensure unique user-company pairs
    UNIQUE(user_id, company_id)
);

-- Indexes for efficient lookups
CREATE INDEX idx_user_companies_user ON user_companies(user_id);
CREATE INDEX idx_user_companies_company ON user_companies(company_id);
CREATE INDEX idx_user_companies_role ON user_companies(role);

-- Comments
COMMENT ON TABLE user_companies IS 'Multi-tenant pivot: links users to companies with specific roles';
COMMENT ON COLUMN user_companies.role IS 'Role within this company: admin or recruiter';
COMMENT ON COLUMN user_companies.permissions IS 'Optional JSON object for granular permissions per company';
