-- Tenant registry schema for MVP Platform Tenants Service
-- Creates core tenant management tables

-- Tenant registry
CREATE TABLE IF NOT EXISTS tenants (
    id VARCHAR(100) PRIMARY KEY,              -- 'admin', 'acme-corp', etc.
    name VARCHAR(255) NOT NULL,               -- Display name
    subdomain VARCHAR(100) UNIQUE NOT NULL,   -- Same as id for simplicity  
    status VARCHAR(50) DEFAULT 'active',      -- active, pending, suspended
    admin_user_id VARCHAR(255),               -- Auth0 user ID of tenant admin
    settings JSONB DEFAULT '{}',              -- Tenant-specific configuration
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Create indexes for performance
CREATE INDEX IF NOT EXISTS idx_tenants_status ON tenants(status);
CREATE INDEX IF NOT EXISTS idx_tenants_admin_user ON tenants(admin_user_id);

-- Tenant signup approval workflow
CREATE TABLE IF NOT EXISTS tenant_signups (
    id SERIAL PRIMARY KEY,
    tenant_id VARCHAR(100) REFERENCES tenants(id),
    user_email VARCHAR(255) NOT NULL,
    user_auth0_id VARCHAR(255),               -- Auth0 user ID after signup
    status VARCHAR(50) DEFAULT 'pending',     -- pending, approved, rejected
    requested_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    approved_by VARCHAR(255),                 -- Auth0 ID of approving admin
    approved_at TIMESTAMP,
    rejected_at TIMESTAMP,
    rejection_reason TEXT
);

-- Create indexes for signup queries
CREATE INDEX IF NOT EXISTS idx_tenant_signups_tenant_status ON tenant_signups(tenant_id, status);
CREATE INDEX IF NOT EXISTS idx_tenant_signups_user_email ON tenant_signups(user_email);

-- Initial admin tenant data
INSERT INTO tenants (id, name, subdomain, status, admin_user_id) 
VALUES ('admin', 'Admin Tenant', 'admin', 'active', NULL)
ON CONFLICT (id) DO NOTHING;
