-- 1. Create tables with timestamps correctly

CREATE TABLE api_key
(
    id               BIGINT GENERATED BY DEFAULT AS IDENTITY NOT NULL,
    api_key          VARCHAR(255)                            NOT NULL,
    type             VARCHAR(255)                            NOT NULL,
    enabled          BOOLEAN                                 NOT NULL,
    frontend_only    BOOLEAN                                 NOT NULL,
    createdDateTime  TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    modifiedDateTime TIMESTAMP NULL,
    CONSTRAINT pk_api_key PRIMARY KEY (id)
);

CREATE TABLE api_key_services
(
    api_key_id       BIGINT NOT NULL,
    allowed_service  VARCHAR(255),
    createdDateTime  TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    modifiedDateTime TIMESTAMP NULL
);

-- 2. Add constraints

ALTER TABLE api_key
    ADD CONSTRAINT uc_api_key_key UNIQUE (api_key); -- (fixed: correct column name is api_key)

ALTER TABLE api_key_services
    ADD CONSTRAINT fk_api_key_services_on_api_key FOREIGN KEY (api_key_id) REFERENCES api_key (id);

-- 3. Function to update modifiedDateTime if any real change occurs

CREATE
OR REPLACE FUNCTION set_modified_datetime()
RETURNS TRIGGER AS $$
BEGIN
  IF
(OLD IS DISTINCT FROM NEW) THEN
    NEW.modifiedDateTime = CURRENT_TIMESTAMP;
END IF;
RETURN NEW;
END;
$$
LANGUAGE plpgsql;

-- 4. Triggers to update modifiedDateTime

CREATE TRIGGER trg_set_modified_datetime_api_key
    BEFORE UPDATE
    ON api_key
    FOR EACH ROW
    EXECUTE FUNCTION set_modified_datetime();

CREATE TRIGGER trg_set_modified_datetime_api_key_services
    BEFORE UPDATE
    ON api_key_services
    FOR EACH ROW
    EXECUTE FUNCTION set_modified_datetime();
