# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 CERN.
#
# Invenio-Vocabularies is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.

"""Vocabulary names."""

from invenio_db import db
from invenio_records.dumpers import SearchDumper
from invenio_records.dumpers.indexedat import IndexedAtDumperExt
from invenio_records.dumpers.relations import RelationDumperExt
from invenio_records.systemfields import RelationsField
from invenio_records_resources.factories.factory import RecordTypeFactory
from invenio_records_resources.records.systemfields import (
    ModelPIDField,
    PIDListRelation,
)

from ...services.permissions import PermissionPolicy
from ..affiliations.api import Affiliation
from .config import NamesSearchOptions, service_components
from .schema import NameSchema

name_relations = RelationsField(
    affiliations=PIDListRelation(
        "affiliations",
        keys=["name"],
        pid_field=Affiliation.pid,
        cache_key="affiliations",
    )
)

record_type = RecordTypeFactory(
    "Name",
    # Data layer
    pid_field_cls=ModelPIDField,
    pid_field_kwargs={
        "model_field_name": "pid",
    },
    model_cls_attrs={
        # cannot set to nullable=False because it would fail at
        # service level when create({}), see records-resources.
        "pid": db.Column(db.String(255), unique=True),
    },
    schema_version="1.0.0",
    schema_path="local://names/name-v1.0.0.json",
    record_relations=name_relations,
    record_dumper=SearchDumper(
        model_fields={"pid": ("id", str)},
        extensions=[
            RelationDumperExt("relations"),
            IndexedAtDumperExt(),
        ],
    ),
    # Service layer
    service_id="names",
    service_schema=NameSchema,
    search_options=NamesSearchOptions,
    service_components=service_components,
    permission_policy_cls=PermissionPolicy,
    # Resource layer
    endpoint_route="/names",
)
