import click
from flask.cli import with_appcontext
from app.extensions import db
from app.core.models import User, Role, Permission, Status, Category
from app.modules.hris.models import Shift
from datetime import time


DEFAULT_PAYROLL_COMPONENTS = [
    # Mandatory earnings (informative/non-cash employer burdens can be mirrored by correction deductions)
    {
        'name': 'Premi BPJS Kesehatan (Perusahaan 4%)',
        'type': 'earning',
        'calculation_type': 'percentage_gross',
        'default_amount': 4.00,
        'is_mandatory': True,
        'is_taxable': True
    },
    {
        'name': 'Premi JHT (Perusahaan 2%)',
        'type': 'earning',
        'calculation_type': 'percentage_gross',
        'default_amount': 2.00,
        'is_mandatory': True,
        'is_taxable': True
    },
    {
        'name': 'Premi JKK (Perusahaan 0.24%)',
        'type': 'earning',
        'calculation_type': 'percentage_gross',
        'default_amount': 0.24,
        'is_mandatory': True,
        'is_taxable': True
    },
    {
        'name': 'Premi JKM (Perusahaan 0.30%)',
        'type': 'earning',
        'calculation_type': 'percentage_gross',
        'default_amount': 0.30,
        'is_mandatory': True,
        'is_taxable': True
    },

    # Optional earnings
    {
        'name': 'Tunjangan Jabatan',
        'type': 'earning',
        'calculation_type': 'percentage_gross',
        'default_amount': 5.00,
        'is_mandatory': False,
        'is_taxable': True
    },
    {
        'name': 'Tunjangan Keluarga',
        'type': 'earning',
        'calculation_type': 'fixed_amount',
        'default_amount': 300000.00,
        'is_mandatory': False,
        'is_taxable': True
    },
    {
        'name': 'Tunjangan Perumahan',
        'type': 'earning',
        'calculation_type': 'fixed_amount',
        'default_amount': 500000.00,
        'is_mandatory': False,
        'is_taxable': True
    },
    {
        'name': 'Tunjangan Kesehatan Tunai',
        'type': 'earning',
        'calculation_type': 'fixed_amount',
        'default_amount': 250000.00,
        'is_mandatory': False,
        'is_taxable': True
    },
    {
        'name': 'Uang Makan Harian',
        'type': 'earning',
        'calculation_type': 'per_occurrence',
        'default_amount': 50000.00,
        'is_mandatory': False,
        'is_taxable': True
    },
    {
        'name': 'Uang Transport Harian',
        'type': 'earning',
        'calculation_type': 'per_occurrence',
        'default_amount': 25000.00,
        'is_mandatory': False,
        'is_taxable': True
    },
    {
        'name': 'Upah Lembur',
        'type': 'earning',
        'calculation_type': 'per_occurrence',
        'default_amount': 50000.00,
        'is_mandatory': False,
        'is_taxable': True
    },
    {
        'name': 'Insentif Kinerja',
        'type': 'earning',
        'calculation_type': 'fixed_amount',
        'default_amount': 0.00,
        'is_mandatory': False,
        'is_taxable': True
    },
    {
        'name': 'Bonus/THR',
        'type': 'earning',
        'calculation_type': 'fixed_amount',
        'default_amount': 0.00,
        'is_mandatory': False,
        'is_taxable': True
    },

    # Mandatory deductions
    {
        'name': 'Premi BPJS Kesehatan (Perusahaan 4%) (Koreksi Non-Tunai)',
        'type': 'deduction',
        'calculation_type': 'percentage_gross',
        'default_amount': 4.00,
        'is_mandatory': True,
        'is_taxable': False
    },
    {
        'name': 'Premi JKK (Perusahaan 0.24%) (Koreksi Non-Tunai)',
        'type': 'deduction',
        'calculation_type': 'percentage_gross',
        'default_amount': 0.24,
        'is_mandatory': True,
        'is_taxable': False
    },
    {
        'name': 'Premi JKM (Perusahaan 0.30%) (Koreksi Non-Tunai)',
        'type': 'deduction',
        'calculation_type': 'percentage_gross',
        'default_amount': 0.30,
        'is_mandatory': True,
        'is_taxable': False
    },
    {
        'name': 'BPJS Kesehatan (Karyawan 1%)',
        'type': 'deduction',
        'calculation_type': 'percentage_gross',
        'default_amount': 1.00,
        'is_mandatory': True,
        'is_taxable': False
    },
    {
        'name': 'Premi JHT (Karyawan 2%)',
        'type': 'deduction',
        'calculation_type': 'percentage_gross',
        'default_amount': 2.00,
        'is_mandatory': True,
        'is_taxable': False
    },
    {
        'name': 'Jaminan Pensiun (Karyawan 1%)',
        'type': 'deduction',
        'calculation_type': 'percentage_gross',
        'default_amount': 1.00,
        'is_mandatory': True,
        'is_taxable': False
    },
    {
        'name': 'PPh 21',
        'type': 'deduction',
        'calculation_type': 'percentage_gross',
        'default_amount': 0.00,
        'is_mandatory': True,
        'is_taxable': False
    },

    # Optional deductions
    {
        'name': 'Potongan Terlambat',
        'type': 'deduction',
        'calculation_type': 'per_occurrence',
        'default_amount': 25000.00,
        'is_mandatory': False,
        'is_taxable': False
    },
    {
        'name': 'Potongan Absen (Alpha)',
        'type': 'deduction',
        'calculation_type': 'per_occurrence',
        'default_amount': 50000.00,
        'is_mandatory': False,
        'is_taxable': False
    },
    {
        'name': 'Potongan Koperasi',
        'type': 'deduction',
        'calculation_type': 'fixed_amount',
        'default_amount': 0.00,
        'is_mandatory': False,
        'is_taxable': False
    },
    {
        'name': 'Potongan Pinjaman Internal',
        'type': 'deduction',
        'calculation_type': 'fixed_amount',
        'default_amount': 0.00,
        'is_mandatory': False,
        'is_taxable': False
    },
]


def seed_default_payroll_components() -> dict:
    """Upserts default payroll components with mandatory/optional classification."""
    from app.modules.hris.models.master import SalaryComponent

    created = 0
    updated = 0
    mandatory = 0
    optional = 0

    # Normalize legacy type naming from old seeds.
    legacy_rows = SalaryComponent.query.filter_by(type='addition').all()
    for row in legacy_rows:
        row.type = 'earning'
        updated += 1

    for payload in DEFAULT_PAYROLL_COMPONENTS:
        component = SalaryComponent.query.filter_by(name=payload['name']).first()
        if not component:
            component = SalaryComponent(**payload)
            db.session.add(component)
            created += 1
        else:
            component.type = payload['type']
            component.calculation_type = payload['calculation_type']
            component.default_amount = payload['default_amount']
            component.is_mandatory = payload['is_mandatory']
            component.is_taxable = payload['is_taxable']
            updated += 1

        if payload['is_mandatory']:
            mandatory += 1
        else:
            optional += 1

    db.session.commit()
    return {
        'created': created,
        'updated': updated,
        'mandatory': mandatory,
        'optional': optional,
        'total': len(DEFAULT_PAYROLL_COMPONENTS)
    }

@click.command('seed-db')
@with_appcontext
def seed_db_command():
    """Seeds the database with initial permissions, statuses, and admin user."""

    # ───────────────────────────────────────────────────────
    # 1. Categories (CRM, HRIS, ERP)
    # ───────────────────────────────────────────────────────
    category_seeds = {
        'crm': ['Customer', 'Vendor', 'Partner', 'Distributor'],
        'hris': ['Permanent', 'Contract', 'Internship', 'Probation'],
        'erp': ['Web Development', 'Mobile App', 'Consulting', 'Support & Maintenance'],
        'erp_expense': ['Server & Hosting', 'Sewa / Rent', 'Listrik & Utilitas', 'Vendor / Supplier', 'Transportasi', 'Employee Reimbursement', 'Lainnya'],
    }
    for module, names in category_seeds.items():
        for name in names:
            slug = name.lower().replace(' ', '_').replace('&', 'and')
            if not Category.query.filter_by(module=module, slug=slug).first():
                db.session.add(Category(module=module, name=name, slug=slug))
                click.echo(f"  Category ({module}): {name}")
    db.session.commit()

    # ───────────────────────────────────────────────────────
    # 2. Shifts
    # ───────────────────────────────────────────────────────
    if not Shift.query.first():
        shifts = [
            Shift(name='Morning Shift', start_time=time(8, 0), end_time=time(17, 0)),
            Shift(name='Night Shift', start_time=time(20, 0), end_time=time(5, 0))
        ]
        db.session.add_all(shifts)
        click.echo("  Created Shifts")

    # ───────────────────────────────────────────────────────
    # 3. Statuses — ALL Modules
    # ───────────────────────────────────────────────────────
    all_statuses = [
        # --- CRM: Lead Pipeline ---
        ('crm', 'leads',     'New',            'new',              'primary',   'NEW'),
        ('crm', 'leads',     'Qualification',  'qualification',    'info',      'PROCESS'),
        ('crm', 'leads',     'Proposal',       'proposal',         'warning',   'PROCESS'),
        ('crm', 'leads',     'Negotiation',    'negotiation',      'warning',   'PROCESS'),
        ('crm', 'leads',     'Won',            'won',              'success',   'FINAL_CONVERTIBLE'),
        ('crm', 'leads',     'Lost',           'lost',             'danger',    'FINAL_CLOSED'),
        # --- CRM: Tickets ---
        ('crm', 'tickets',   'Open',           'ticket_open',      'primary',   'NEW'),
        ('crm', 'tickets',   'In Progress',    'ticket_in_progress','info',     'PROCESS'),
        ('crm', 'tickets',   'Resolved',       'ticket_resolved',  'success',   'FINAL_CLOSED'),
        ('crm', 'tickets',   'Closed',         'ticket_closed',    'secondary', 'FINAL_CLOSED'),

        # --- ERP: Projects ---
        ('erp', 'projects',  'Development',    'proj_dev',         'primary',   'PROCESS'),
        ('erp', 'projects',  'UAT',            'proj_uat',         'warning',   'PROCESS'),
        ('erp', 'projects',  'Live',           'proj_live',        'success',   'FINAL_CLOSED'),
        ('erp', 'projects',  'Maintenance',    'proj_maint',       'info',      'PROCESS'),
        # --- ERP: Invoices ---
        ('erp', 'invoices',  'Draft',          'inv_draft',        'secondary', 'NEW'),
        ('erp', 'invoices',  'Sent',           'inv_sent',         'primary',   'PROCESS'),
        ('erp', 'invoices',  'Partial Paid',   'inv_partial',      'info',      'PROCESS'),
        ('erp', 'invoices',  'Paid',           'inv_paid',         'success',   'FINAL_CLOSED'),
        ('erp', 'invoices',  'Overdue',        'inv_overdue',      'danger',    'FINAL_CLOSED'),
        # --- ERP: Planner Tasks ---
        ('erp', 'planner',   'To Do',          'task_todo',        'secondary', 'NEW'),
        ('erp', 'planner',   'In Progress',    'task_doing',       'primary',   'PROCESS'),
        ('erp', 'planner',   'Review',         'task_review',      'info',      'PROCESS'),
        ('erp', 'planner',   'Blocked',        'task_blocked',     'danger',    'PROCESS'),
        ('erp', 'planner',   'Done',           'task_done',        'success',   'FINAL_CLOSED'),

        # --- HRIS: Attendance ---
        ('hris', 'attendance','Present',       'attn_present',     'success',   'FINAL_CLOSED'),
        ('hris', 'attendance','Late',          'attn_late',        'warning',   'FINAL_CLOSED'),
        ('hris', 'attendance','Absent',        'attn_absent',      'danger',    'FINAL_CLOSED'),
        ('hris', 'attendance','Half-Day',      'attn_half',        'info',      'FINAL_CLOSED'),
        ('hris', 'attendance','On Work',       'attn_onwork',      'primary',   'PROCESS'),
        ('hris', 'attendance','Undertime',     'attn_undertime',   'warning',   'FINAL_CLOSED'),
        ('hris', 'attendance','Overtime',      'attn_overtime',    'info',      'FINAL_CLOSED'),
        # --- HRIS: Leave ---
        ('hris', 'leave',     'Pending',       'leave_pending',    'secondary', 'PROCESS'),
        ('hris', 'leave',     'Approved',      'leave_approved',   'success',   'FINAL_CLOSED'),
        ('hris', 'leave',     'Rejected',      'leave_rejected',   'danger',    'FINAL_CLOSED'),
        # --- HRIS: Leave Type ---
        ('hris', 'leave_type', 'Cuti Tahunan', 'leave_type_tahunan', 'primary', 'no_attachment'),
        ('hris', 'leave_type', 'Sakit',        'leave_type_sakit',   'danger',  'requires_attachment'),
        ('hris', 'leave_type', 'Izin Darurat', 'leave_type_izin',    'warning', 'no_attachment'),
        ('hris', 'leave_type', 'Unpaid Leave', 'leave_type_unpaid',  'dark',    'no_attachment'),
        ('hris', 'leave_type', 'Cuti Melahirkan', 'leave_type_melahirkan', 'info', 'requires_attachment'),
        ('hris', 'leave_type', 'Cuti Menikah', 'leave_type_menikah', 'primary', 'no_attachment'),
        ('hris', 'leave_type', 'Cuti Duka Cita', 'leave_type_duka',  'secondary', 'no_attachment'),
        # --- HRIS: Reimbursement ---
        ('hris', 'reimbursement','Pending',    'reimb_pending',    'secondary', 'PROCESS'),
        ('hris', 'reimbursement','Approved',   'reimb_approved',   'success',   'PROCESS'),
        ('hris', 'reimbursement','Paid',       'reimb_paid',       'success',   'FINAL_CLOSED'),
        ('hris', 'reimbursement','Rejected',   'reimb_rejected',   'danger',    'FINAL_CLOSED'),
        # --- HRIS: Payslip ---
        ('hris', 'payslip',   'Draft',         'payslip_draft',    'secondary', 'NEW'),
        ('hris', 'payslip',   'Paid',          'payslip_paid',     'success',   'FINAL_CLOSED'),

        # --- CORE: Employee Status ---
        ('core', 'employee',  'Active',        'emp_active',       'success',   'ACTIVE'),
        ('core', 'employee',  'Resigned',      'emp_resigned',     'secondary', 'RESIGNED'),
        ('core', 'employee',  'Terminated',    'emp_terminated',   'danger',    'TERMINATED'),
        ('core', 'employee',  'Suspended',     'emp_suspended',    'warning',   'SUSPENDED'),
    ]

    for module, sub_module, name, slug, color, tag in all_statuses:
        if not Status.query.filter_by(slug=slug).first():
            db.session.add(Status(module=module, sub_module=sub_module, name=name, slug=slug, color=color, system_tag=tag))
            click.echo(f"  Status ({module}/{sub_module or 'global'}): {name} [{slug}]")
    db.session.commit()

    # ───────────────────────────────────────────────────────
    # 4. Default Module Settings
    # ───────────────────────────────────────────────────────
    from app.core.models import Settings
    default_modules = [
        ('module_crm_enabled', 'true'),
        ('module_erp_enabled', 'true'),
        ('module_hris_enabled', 'true'),
        ('module_collab_enabled', 'true'),
    ]
    for key, val in default_modules:
        if not Settings.query.filter_by(key=key).first():
            db.session.add(Settings(group='system', key=key, value=val, type='boolean'))
            click.echo(f"  Module: {key}")
    db.session.commit()

    # ───────────────────────────────────────────────────────
    # 5. Permissions
    # ───────────────────────────────────────────────────────
    permissions_list = [
        # Dashboard Access
        ('dashboard.view', 'View Management Dashboard'),
        # User Management
        ('user.view', 'View Users'),
        ('user.create', 'Create Users'),
        ('user.edit', 'Edit Users'),
        ('user.delete', 'Delete Users'),
        # Role Management
        ('role.view', 'View Roles'),
        ('role.manage', 'Manage Roles'),
        # Audit
        ('audit.view', 'View Audit Logs'),
        # Core Models (Decoupled from HRIS)
        ('employee.view', 'View Employees'),
        ('employee.manage', 'Manage Employees'),
        # Module Access
        ('crm.access', 'Access CRM Module'),
        ('crm.manage', 'Manage CRM (Leads & Tickets)'),
        ('crm.leads.manage', 'Manage All Leads'),
        ('crm.tickets.manage', 'Manage All Tickets'),
        ('crm.override', 'Bypass Restrictions in CRM'),
        ('erp.access', 'Access ERP Module'),
        ('erp.manage', 'Manage ERP (Projects & Finance)'),
        ('erp.projects.manage', 'Manage All Projects'),
        ('erp.finance.manage', 'Manage Finances'),
        ('erp.override', 'Bypass Restrictions in ERP'),
        ('hris.access', 'Access HRIS Module'),
        ('hris.manage', 'Manage HRIS (Admin/HR)'),
        ('hris.override', 'Bypass Restrictions in HRIS'),
        ('collab.access', 'Access Collaboration Module'),
        ('settings.manage', 'Manage System Settings'),
    ]

    created_perms = []
    for slug, desc in permissions_list:
        perm = Permission.query.filter_by(slug=slug).first()
        if not perm:
            perm = Permission(slug=slug, description=desc)
            db.session.add(perm)
            click.echo(f"  Permission: {slug}")
        created_perms.append(perm)
    db.session.commit()

    # ───────────────────────────────────────────────────────
    # 6. Roles
    # ───────────────────────────────────────────────────────
    # Admin — all permissions
    admin_role = Role.query.filter_by(name='Admin').first()
    if not admin_role:
        admin_role = Role(name='Admin')
        db.session.add(admin_role)
        click.echo("  Role: Admin")
    admin_role.permissions = created_perms
    db.session.commit()

    # User — standard employee access
    user_role = Role.query.filter_by(name='User').first()
    if not user_role:
        user_role = Role(name='User')
        db.session.add(user_role)
        click.echo("  Role: User")
    user_perms = [p for p in created_perms if p.slug in [
        'crm.access', 'erp.access', 'hris.access', 'collab.access'
    ]]
    user_role.permissions = user_perms
    db.session.commit()

    # General Manager - Broad Access & Management
    gm_role = Role.query.filter_by(name='General Manager').first()
    if not gm_role:
        gm_role = Role(name='General Manager')
        db.session.add(gm_role)
        click.echo("  Role: General Manager")
    gm_perms = [p for p in created_perms if p.slug in [
        'crm.access', 'crm.manage', 'crm.leads.manage', 'crm.tickets.manage', 
        'erp.access', 'erp.manage', 'erp.projects.manage', 'erp.finance.manage',
        'hris.access', 'hris.manage', 'collab.access', 'employee.view',
        'crm.override', 'erp.override', 'hris.override', 'settings.manage'
    ]]
    gm_role.permissions = gm_perms
    db.session.commit()

    # HR Manager - HR access + manage
    hr_role = Role.query.filter_by(name='HR Manager').first()
    if not hr_role:
        hr_role = Role(name='HR Manager')
        db.session.add(hr_role)
        click.echo("  Role: HR Manager")
    hr_perms = [p for p in created_perms if p.slug in [
        'hris.access', 'hris.manage', 'employee.view', 'employee.manage', 'hris.override'
    ]]
    hr_role.permissions = hr_perms
    db.session.commit()

    # Sales Manager
    sm_role = Role.query.filter_by(name='Sales Manager').first()
    if not sm_role:
        sm_role = Role(name='Sales Manager')
        db.session.add(sm_role)
        click.echo("  Role: Sales Manager")
    sm_perms = [p for p in created_perms if p.slug in ['crm.access', 'crm.manage', 'crm.leads.manage', 'crm.override', 'collab.access']]
    sm_role.permissions = sm_perms
    db.session.commit()

    # Sales Agent
    sa_role = Role.query.filter_by(name='Sales Agent').first()
    if not sa_role:
        sa_role = Role(name='Sales Agent')
        db.session.add(sa_role)
        click.echo("  Role: Sales Agent")
    sa_perms = [p for p in created_perms if p.slug in ['crm.access', 'collab.access']]
    sa_role.permissions = sa_perms
    db.session.commit()

    # Support Manager
    supm_role = Role.query.filter_by(name='Support Manager').first()
    if not supm_role:
        supm_role = Role(name='Support Manager')
        db.session.add(supm_role)
        click.echo("  Role: Support Manager")
    supm_perms = [p for p in created_perms if p.slug in ['dashboard.view', 'crm.access', 'crm.manage', 'crm.tickets.manage', 'crm.override', 'collab.access']]
    supm_role.permissions = supm_perms
    db.session.commit()

    # Support Agent
    supa_role = Role.query.filter_by(name='Support Agent').first()
    if not supa_role:
        supa_role = Role(name='Support Agent')
        db.session.add(supa_role)
        click.echo("  Role: Support Agent")
    supa_perms = [p for p in created_perms if p.slug in ['crm.access', 'collab.access']]
    supa_role.permissions = supa_perms
    db.session.commit()

    # Project Manager
    pm_role = Role.query.filter_by(name='Project Manager').first()
    if not pm_role:
        pm_role = Role(name='Project Manager')
        db.session.add(pm_role)
        click.echo("  Role: Project Manager")
    pm_perms = [p for p in created_perms if p.slug in ['dashboard.view', 'erp.access', 'erp.projects.manage', 'erp.override', 'collab.access']]
    pm_role.permissions = pm_perms
    db.session.commit()

    # Finance
    fin_role = Role.query.filter_by(name='Finance').first()
    if not fin_role:
        fin_role = Role(name='Finance')
        db.session.add(fin_role)
        click.echo("  Role: Finance")
    fin_perms = [p for p in created_perms if p.slug in ['dashboard.view', 'erp.access', 'erp.finance.manage', 'collab.access']]
    fin_role.permissions = fin_perms
    db.session.commit()

    # ───────────────────────────────────────────────────────
    # 7. Default Admin User
    # ───────────────────────────────────────────────────────
    admin_email = 'admin@example.com'
    admin = User.query.filter_by(email=admin_email).first()
    if not admin:
        admin = User(email=admin_email, role=admin_role)
        admin.set_password('admin123')
        db.session.add(admin)
        click.echo(f"  Admin User: {admin_email} / admin123")
    else:
        admin.role = admin_role

    db.session.commit()

    # ───────────────────────────────────────────────────────
    # 8. Default Main Office
    # ───────────────────────────────────────────────────────
    from app.core.models import Office
    main_office = Office.query.filter_by(name='Main Office').first()
    if not main_office:
        main_office = Office(
            name='Main Office', 
            address='123 Central Business District', 
            latitude=-6.200000, 
            longitude=106.816666, 
            radius_meters=100
        )
        db.session.add(main_office)
        click.echo("  Office: Main Office Created")

    # ───────────────────────────────────────────────────────
    # 9. Default Payroll Components
    # ───────────────────────────────────────────────────────
    component_result = seed_default_payroll_components()
    click.echo(
        "  Payroll Components: "
        f"total={component_result['total']} "
        f"mandatory={component_result['mandatory']} "
        f"optional={component_result['optional']} "
        f"created={component_result['created']} "
        f"updated={component_result['updated']}"
    )

    db.session.commit()
    click.echo("\nOK Database seeding completed.")

def init_app(app):
    app.cli.add_command(seed_db_command)
    app.cli.add_command(seed_hris_command)

@click.command('seed-hris')
@with_appcontext
def seed_hris_command():
    """Seeds the database with HRIS default Components and PPh21 TER Rates."""
    from app.modules.hris.models.tax import Pph21TerRate, TerCategory

    click.echo("Seeding HRIS Components...")
    component_result = seed_default_payroll_components()
    click.echo(
        "  > Payroll Components: "
        f"total={component_result['total']} "
        f"mandatory={component_result['mandatory']} "
        f"optional={component_result['optional']} "
        f"created={component_result['created']} "
        f"updated={component_result['updated']}"
    )

    click.echo("Seeding PPh21 TER Rates...")
    ter_data = [
        # Kategori A
        (TerCategory.A, 0.00, 5400000.00, 0.00),
        (TerCategory.A, 5400000.01, 5650000.00, 0.25),
        (TerCategory.A, 5650000.01, 5950000.00, 0.50),
        (TerCategory.A, 5950000.01, 6300000.00, 0.75),
        (TerCategory.A, 6300000.01, 6750000.00, 1.00),
        (TerCategory.A, 6750000.01, 7500000.00, 1.25),
        (TerCategory.A, 7500000.01, 8550000.00, 1.50),
        (TerCategory.A, 8550000.01, 9650000.00, 1.75),
        (TerCategory.A, 9650000.01, 10050000.00, 2.00),
        (TerCategory.A, 10050000.01, 10350000.00, 2.25),
        (TerCategory.A, 10350000.01, 10700000.00, 2.50),
        (TerCategory.A, 10700000.01, 11050000.00, 3.00),
        (TerCategory.A, 11050000.01, 11600000.00, 3.50),
        (TerCategory.A, 11600000.01, 12500000.00, 4.00),
        (TerCategory.A, 12500000.01, 13750000.00, 5.00),
        (TerCategory.A, 13750000.01, 15100000.00, 6.00),
        (TerCategory.A, 15100000.01, 16950000.00, 7.00),
        (TerCategory.A, 16950000.01, 19750000.00, 8.00),
        (TerCategory.A, 19750000.01, 24150000.00, 9.00),
        (TerCategory.A, 24150000.01, 26450000.00, 10.00),
        (TerCategory.A, 26450000.01, 28000000.00, 11.00),
        (TerCategory.A, 28000000.01, 30050000.00, 12.00),
        (TerCategory.A, 30050000.01, 32400000.00, 13.00),
        (TerCategory.A, 32400000.01, 35400000.00, 14.00),
        (TerCategory.A, 35400000.01, 39100000.00, 15.00),
        (TerCategory.A, 39100000.01, 43850000.00, 16.00),
        (TerCategory.A, 43850000.01, 47800000.00, 17.00),
        (TerCategory.A, 47800000.01, 51400000.00, 18.00),
        (TerCategory.A, 51400000.01, 56300000.00, 19.00),
        (TerCategory.A, 56300000.01, 62200000.00, 20.00),
        (TerCategory.A, 62200000.01, 68600000.00, 21.00),
        (TerCategory.A, 68600000.01, 77500000.00, 22.00),
        (TerCategory.A, 77500000.01, 89000000.00, 23.00),
        (TerCategory.A, 89000000.01, 103000000.00, 24.00),
        (TerCategory.A, 103000000.01, 125000000.00, 25.00),
        (TerCategory.A, 125000000.01, 157000000.00, 26.00),
        (TerCategory.A, 157000000.01, 206000000.00, 27.00),
        (TerCategory.A, 206000000.01, 337000000.00, 28.00),
        (TerCategory.A, 337000000.01, 454000000.00, 29.00),
        (TerCategory.A, 454000000.01, 550000000.00, 30.00),
        (TerCategory.A, 550000000.01, 695000000.00, 31.00),
        (TerCategory.A, 695000000.01, 910000000.00, 32.00),
        (TerCategory.A, 910000000.01, 1400000000.00, 33.00),
        (TerCategory.A, 1400000000.01, 999999999999.99, 34.00),

        # Kategori B
        (TerCategory.B, 0.00, 6200000.00, 0.00),
        (TerCategory.B, 6200000.01, 6500000.00, 0.25),
        (TerCategory.B, 6500000.01, 6850000.00, 0.50),
        (TerCategory.B, 6850000.01, 7300000.00, 0.75),
        (TerCategory.B, 7300000.01, 9200000.00, 1.00),
        (TerCategory.B, 9200000.01, 10750000.00, 1.50),
        (TerCategory.B, 10750000.01, 11250000.00, 2.00),
        (TerCategory.B, 11250000.01, 11600000.00, 2.50),
        (TerCategory.B, 11600000.01, 12600000.00, 3.00),
        (TerCategory.B, 12600000.01, 13600000.00, 4.00),
        (TerCategory.B, 13600000.01, 14950000.00, 5.00),
        (TerCategory.B, 14950000.01, 16400000.00, 6.00),
        (TerCategory.B, 16400000.01, 18450000.00, 7.00),
        (TerCategory.B, 18450000.01, 21850000.00, 8.00),
        (TerCategory.B, 21850000.01, 26000000.00, 9.00),
        (TerCategory.B, 26000000.01, 27700000.00, 10.00),
        (TerCategory.B, 27700000.01, 29350000.00, 11.00),
        (TerCategory.B, 29350000.01, 31450000.00, 12.00),
        (TerCategory.B, 31450000.01, 33950000.00, 13.00),
        (TerCategory.B, 33950000.01, 37100000.00, 14.00),
        (TerCategory.B, 37100000.01, 41100000.00, 15.00),
        (TerCategory.B, 41100000.01, 45800000.00, 16.00),
        (TerCategory.B, 45800000.01, 49500000.00, 17.00),
        (TerCategory.B, 49500000.01, 53800000.00, 18.00),
        (TerCategory.B, 53800000.01, 58500000.00, 19.00),
        (TerCategory.B, 58500000.01, 64000000.00, 20.00),
        (TerCategory.B, 64000000.01, 71000000.00, 21.00),
        (TerCategory.B, 71000000.01, 80000000.00, 22.00),
        (TerCategory.B, 80000000.01, 93000000.00, 23.00),
        (TerCategory.B, 93000000.01, 109000000.00, 24.00),
        (TerCategory.B, 109000000.01, 129000000.00, 25.00),
        (TerCategory.B, 129000000.01, 163000000.00, 26.00),
        (TerCategory.B, 163000000.01, 211000000.00, 27.00),
        (TerCategory.B, 211000000.01, 374000000.00, 28.00),
        (TerCategory.B, 374000000.01, 459000000.00, 29.00),
        (TerCategory.B, 459000000.01, 555000000.00, 30.00),
        (TerCategory.B, 555000000.01, 704000000.00, 31.00),
        (TerCategory.B, 704000000.01, 957000000.00, 32.00),
        (TerCategory.B, 957000000.01, 1405000000.00, 33.00),
        (TerCategory.B, 1405000000.01, 999999999999.99, 34.00),

        # Kategori C
        (TerCategory.C, 0.00, 6600000.00, 0.00),
        (TerCategory.C, 6600000.01, 6950000.00, 0.25),
        (TerCategory.C, 6950000.01, 7350000.00, 0.50),
        (TerCategory.C, 7350000.01, 7800000.00, 0.75),
        (TerCategory.C, 7800000.01, 8850000.00, 1.00),
        (TerCategory.C, 8850000.01, 9800000.00, 1.25),
        (TerCategory.C, 9800000.01, 10950000.00, 1.50),
        (TerCategory.C, 10950000.01, 11200000.00, 1.75),
        (TerCategory.C, 11200000.01, 12050000.00, 2.00),
        (TerCategory.C, 12050000.01, 12950000.00, 3.00),
        (TerCategory.C, 12950000.01, 14150000.00, 4.00),
        (TerCategory.C, 14150000.01, 15550000.00, 5.00),
        (TerCategory.C, 15550000.01, 17050000.00, 6.00),
        (TerCategory.C, 17050000.01, 19500000.00, 7.00),
        (TerCategory.C, 19500000.01, 22700000.00, 8.00),
        (TerCategory.C, 22700000.01, 26600000.00, 9.00),
        (TerCategory.C, 26600000.01, 28100000.00, 10.00),
        (TerCategory.C, 28100000.01, 30100000.00, 11.00),
        (TerCategory.C, 30100000.01, 32600000.00, 12.00),
        (TerCategory.C, 32600000.01, 35400000.00, 13.00),
        (TerCategory.C, 35400000.01, 38900000.00, 14.00),
        (TerCategory.C, 38900000.01, 43000000.00, 15.00),
        (TerCategory.C, 43000000.01, 47400000.00, 16.00),
        (TerCategory.C, 47400000.01, 51200000.00, 17.00),
        (TerCategory.C, 51200000.01, 55800000.00, 18.00),
        (TerCategory.C, 55800000.01, 60400000.00, 19.00),
        (TerCategory.C, 60400000.01, 66700000.00, 20.00),
        (TerCategory.C, 66700000.01, 74500000.00, 21.00),
        (TerCategory.C, 74500000.01, 83200000.00, 22.00),
        (TerCategory.C, 83200000.01, 95000000.00, 23.00),
        (TerCategory.C, 95600000.01, 110000000.00, 24.00),
        (TerCategory.C, 110000000.01, 134000000.00, 25.00),
        (TerCategory.C, 134000000.01, 169000000.00, 26.00),
        (TerCategory.C, 169000000.01, 221000000.00, 27.00),
        (TerCategory.C, 221000000.01, 390000000.00, 28.00),
        (TerCategory.C, 390000000.01, 463000000.00, 29.00),
        (TerCategory.C, 463000000.01, 561000000.00, 30.00),
        (TerCategory.C, 561000000.01, 709000000.00, 31.00),
        (TerCategory.C, 709000000.01, 965000000.00, 32.00),
        (TerCategory.C, 965000000.01, 1419000000.00, 33.00),
        (TerCategory.C, 1419000000.01, 999999999999.99, 34.00)
    ]

    # Clean existing rates since they're tightly coupled with logic and updates
    db.session.query(Pph21TerRate).delete()

    count_ter = 0
    for cat, g_min, g_max, rate in ter_data:
        rule = Pph21TerRate(
            category=cat,
            gross_income_min=g_min,
            gross_income_max=g_max,
            rate_percent=rate
        )
        db.session.add(rule)
        count_ter += 1
    
    db.session.commit()
    click.echo(f"  > Seeded {count_ter} TER Rates.")

    click.echo("\nOK HRIS Additional Database seeding completed.")

