"""Checker for identity generated by default."""

from pglast import ast, enums, visitors

from pgrubic.core import linter


class IdentityGeneratedByDefault(linter.BaseChecker):
    """## **What it does**
    Checks for identity generated by default.

    ## **Why not?**
    **GENERATED BY DEFAULT** allows you to specify a value for insert or update on an
    identity column instead of system generated value. This is usually not what you
    want for an identity column.

    ## **When should you?**
    If you want to be able to specify a value for insert or update on an identity
    column instead of system generated value.

    ## **Use instead:**
    **GENERATED ALWAYS**
    """

    is_auto_fixable: bool = True

    def visit_Constraint(
        self,
        ancestors: visitors.Ancestor,
        node: ast.Constraint,
    ) -> None:
        """Visit Constraint."""
        if (
            node.contype == enums.ConstrType.CONSTR_IDENTITY
            and node.generated_when == enums.ATTRIBUTE_IDENTITY_BY_DEFAULT
        ):
            self.violations.add(
                linter.Violation(
                    rule_code=self.code,
                    rule_name=self.name,
                    rule_category=self.category,
                    line_number=self.line_number,
                    column_offset=self.column_offset,
                    line=self.line,
                    statement_location=self.statement_location,
                    description="Prefer generated always over generated by default identity",  # noqa: E501
                    is_auto_fixable=self.is_auto_fixable,
                    is_fix_enabled=self.is_fix_enabled,
                    help="Use generated always",
                ),
            )

            self._fix(node)

    def _fix(self, node: ast.Constraint) -> None:
        """Fix violation."""
        node.generated_when = enums.ATTRIBUTE_IDENTITY_ALWAYS
