CREATE TABLE ai_plans (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    code VARCHAR(50) UNIQUE NOT NULL,
    name VARCHAR(100) NOT NULL,
    monthly_credits INT NOT NULL,
    daily_action_limit INT NOT NULL,
    allowed_models JSONB NOT NULL,
    allowed_features JSONB NOT NULL,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE TABLE user_ai_subscriptions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID UNIQUE NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    plan_id UUID NOT NULL REFERENCES ai_plans(id),
    role_code VARCHAR(50),
    monthly_credits_total INT NOT NULL,
    monthly_credits_used INT NOT NULL DEFAULT 0,
    purchased_credits_total INT NOT NULL DEFAULT 0,
    purchased_credits_used INT NOT NULL DEFAULT 0,
    daily_actions_used INT NOT NULL DEFAULT 0,
    current_period_start TIMESTAMP NOT NULL,
    current_period_end TIMESTAMP NOT NULL,
    status VARCHAR(30) NOT NULL DEFAULT 'active',
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE TABLE ai_feature_costs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    feature_code VARCHAR(100) UNIQUE NOT NULL,
    display_name VARCHAR(150) NOT NULL,
    default_model VARCHAR(100) NOT NULL,
    credit_cost INT NOT NULL,
    max_input_tokens INT,
    max_output_tokens INT,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE TABLE ai_usage_logs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id),
    role_code VARCHAR(50),
    feature_code VARCHAR(100) NOT NULL,
    model_alias VARCHAR(100) NOT NULL,
    credits_charged INT NOT NULL,
    input_tokens INT,
    output_tokens INT,
    total_tokens INT,
    status VARCHAR(30) NOT NULL,
    request_id VARCHAR(100),
    error_message TEXT,
    created_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE TABLE ai_credit_transactions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id),
    transaction_type VARCHAR(50) NOT NULL,
    source VARCHAR(50) NOT NULL,
    credits INT NOT NULL,
    balance_after INT NOT NULL,
    reference_id UUID,
    description TEXT,
    created_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE TABLE ai_auto_apply_settings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID UNIQUE NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    is_enabled BOOLEAN NOT NULL DEFAULT FALSE,
    preferred_titles JSONB,
    preferred_locations JSONB,
    preferred_job_types JSONB,
    preferred_work_modes JSONB,
    preferred_skills JSONB,
    min_salary INT,
    max_salary INT,
    max_applications_per_day INT NOT NULL DEFAULT 3,
    require_user_approval BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE TABLE ai_auto_apply_logs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id),
    job_id UUID NOT NULL,
    match_score INT,
    status VARCHAR(50) NOT NULL,
    credits_charged INT NOT NULL DEFAULT 0,
    generated_cover_letter TEXT,
    applied_at TIMESTAMP,
    created_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE TABLE ai_auto_request_settings (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID UNIQUE NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    professional_role_code VARCHAR(50) NOT NULL,
    is_enabled BOOLEAN NOT NULL DEFAULT FALSE,
    preferred_categories JSONB,
    preferred_locations JSONB,
    preferred_requirement_types JSONB,
    min_budget INT,
    max_budget INT,
    max_requests_per_day INT NOT NULL DEFAULT 3,
    require_user_approval BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE TABLE ai_auto_request_logs (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id),
    requirement_id UUID NOT NULL,
    professional_role_code VARCHAR(50) NOT NULL,
    match_score INT,
    status VARCHAR(50) NOT NULL,
    credits_charged INT NOT NULL DEFAULT 0,
    requested_at TIMESTAMP,
    created_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_user_ai_subscriptions_user_id ON user_ai_subscriptions(user_id);
CREATE INDEX idx_user_ai_subscriptions_plan_id ON user_ai_subscriptions(plan_id);
CREATE INDEX idx_ai_usage_logs_user_id ON ai_usage_logs(user_id);
CREATE INDEX idx_ai_usage_logs_feature_code ON ai_usage_logs(feature_code);
CREATE INDEX idx_ai_usage_logs_created_at ON ai_usage_logs(created_at);
CREATE INDEX idx_ai_credit_transactions_user_id ON ai_credit_transactions(user_id);
CREATE INDEX idx_ai_auto_apply_logs_user_id ON ai_auto_apply_logs(user_id);
CREATE INDEX idx_ai_auto_apply_logs_job_id ON ai_auto_apply_logs(job_id);
CREATE INDEX idx_ai_auto_request_logs_user_id ON ai_auto_request_logs(user_id);
CREATE INDEX idx_ai_auto_request_logs_requirement_id ON ai_auto_request_logs(requirement_id);

INSERT INTO ai_plans (code, name, monthly_credits, daily_action_limit, allowed_models, allowed_features) VALUES
('free', 'Free', 10, 3, '["askash-fast"]', '["help_answer", "platform_guidance", "form_fill", "form_validate", "jd_generate"]'),
('pro', 'Pro', 100, 15, '["askash-fast", "askash-main"]', '["help_answer", "platform_guidance", "form_fill", "form_validate", "job_match", "auto_apply_suggest", "auto_apply_execute", "cover_letter_generate", "requirement_match", "auto_request_suggest", "auto_request_execute"]'),
('business', 'Business', 300, 40, '["askash-fast", "askash-main"]', '["help_answer", "platform_guidance", "form_fill", "form_validate", "jd_generate", "jd_improve", "skills_extract", "candidate_match", "candidate_shortlist"]'),
('enterprise', 'Enterprise', 50000, 999999, '["askash-fast", "askash-main"]', '["help_answer", "platform_guidance", "form_fill", "form_validate", "jd_generate", "jd_improve", "skills_extract", "candidate_match", "candidate_shortlist", "job_match", "auto_apply_suggest", "auto_apply_execute", "cover_letter_generate", "requirement_match", "auto_request_suggest", "auto_request_execute", "admin_support_reply", "admin_ticket_summary", "admin_verification_summary", "abuse_check"]');

INSERT INTO ai_feature_costs (feature_code, display_name, default_model, credit_cost) VALUES
('help_answer', 'Help Answer', 'askash-fast', 1),
('platform_guidance', 'Platform Guidance', 'askash-fast', 1),
('form_fill', 'Form Fill', 'askash-fast', 2),
('form_validate', 'Form Validate', 'askash-fast', 1),
('jd_generate', 'Job Description Generate', 'askash-main', 5),
('jd_improve', 'Job Description Improve', 'askash-main', 4),
('skills_extract', 'Skills Extract', 'askash-fast', 1),
('candidate_match', 'Candidate Match', 'askash-fast', 1),
('candidate_shortlist', 'Candidate Shortlist', 'askash-fast', 2),
('job_match', 'Job Match', 'askash-fast', 1),
('auto_apply_suggest', 'Auto Apply Suggest', 'askash-fast', 2),
('auto_apply_execute', 'Auto Apply Execute', 'askash-main', 5),
('cover_letter_generate', 'Cover Letter Generate', 'askash-main', 5),
('requirement_match', 'Requirement Match', 'askash-fast', 1),
('auto_request_suggest', 'Auto Request Suggest', 'askash-fast', 2),
('auto_request_execute', 'Auto Request Execute', 'backend', 3),
('admin_support_reply', 'Admin Support Reply', 'askash-main', 3),
('admin_ticket_summary', 'Admin Ticket Summary', 'askash-fast', 1),
('admin_verification_summary', 'Admin Verification Summary', 'askash-fast', 1),
('abuse_check', 'Abuse Check', 'askash-fast', 1);
