-- Migration: Create job_payments table
-- Description: Track payments for job postings

CREATE TABLE IF NOT EXISTS job_payments (
    id UUID PRIMARY KEY DEFAULT uuid_generate_v7(),
    job_id UUID NOT NULL,
    user_id UUID,
    
    -- Stripe
    stripe_session_id VARCHAR(255),
    stripe_payment_intent VARCHAR(255),
    stripe_customer_id VARCHAR(255),
    
    -- Amount
    amount DECIMAL(12,2) NOT NULL,
    currency VARCHAR(3) DEFAULT 'USD',
    
    -- Status
    status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'completed', 'failed', 'refunded', 'expired')),
    
    -- Billing Info
    billing_type VARCHAR(20) CHECK (billing_type IN ('company', 'individual')),
    billing_name VARCHAR(255),
    billing_email VARCHAR(255),
    billing_phone VARCHAR(50),
    billing_address TEXT,
    billing_city VARCHAR(100),
    billing_state VARCHAR(100),
    billing_zip VARCHAR(20),
    billing_country VARCHAR(2) DEFAULT 'BR',
    
    -- Job Posting Details
    duration_days INT DEFAULT 30,
    is_featured BOOLEAN DEFAULT false,
    featured_price DECIMAL(12,2) DEFAULT 0,
    
    -- Timestamps
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    paid_at TIMESTAMP,
    expires_at TIMESTAMP,
    
    -- Foreign key
    FOREIGN KEY (job_id) REFERENCES jobs(id) ON DELETE CASCADE,
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
);

-- Indexes
CREATE INDEX idx_job_payments_job_id ON job_payments(job_id);
CREATE INDEX idx_job_payments_status ON job_payments(status);
CREATE INDEX idx_job_payments_stripe_session ON job_payments(stripe_session_id);
CREATE INDEX idx_job_payments_user ON job_payments(user_id);

-- Comments
COMMENT ON TABLE job_payments IS 'Payment records for job postings';
COMMENT ON COLUMN job_payments.duration_days IS 'How many days the job posting is active';
COMMENT ON COLUMN job_payments.is_featured IS 'Whether this is a featured/sponsored listing';

-- Add job_posting_price table for pricing configuration
CREATE TABLE IF NOT EXISTS job_posting_prices (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    description TEXT,
    price DECIMAL(12,2) NOT NULL,
    currency VARCHAR(3) DEFAULT 'USD',
    duration_days INT DEFAULT 30,
    is_featured BOOLEAN DEFAULT false,
    stripe_price_id VARCHAR(255),
    active BOOLEAN DEFAULT true,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Insert default pricing
INSERT INTO job_posting_prices (name, description, price, currency, duration_days, is_featured, active)
VALUES 
    ('Standard Job Posting', 'Your job will be visible for 30 days', 32.61, 'USD', 30, false, true),
    ('Featured Job Posting', 'Your job will be featured and visible for 30 days', 47.61, 'USD', 30, true, true);
