/*
 * RiskScape™ Copyright New Zealand Institute for Earth Science Limited
 * (Earth Sciences New Zealand) is distributed for research purposes only
 * under the terms of AGPLv3.
 *
 * RiskScape™ Copyright 2026 New Zealand Institute for Earth Science
 * Limited (Earth Sciences New Zealand). All rights reserved. Source code
 * available under the AGPLv3.
 * 
 * This program is free software: you can redistribute it and/or modify it under
 *  the terms of the GNU Affero General Public License as published by the Free
 *  Software Foundation, either version 3 of the License, or (at your option) any
 *  later version.
 * 
 * This program is distributed for RESEARCH PURPOSES ONLY, in the hope that it will
 * be useful for research and education initiatives.
 * 
 * If you are not a researcher, or you are a researcher who wishes to use this
 * program on terms other than AGPLv3 (including those who wish to restrict the
 * distribution of any source code created using this program), please contact:
 * https://riskscape.org.nz
 * 
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.  You should have received a copy
 * of the GNU Affero General Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 * 
 * By way of summary only, under the AGPLv3:
 *     • Permissions of this strongest copyleft license are conditioned
 *       on making available complete source code of licensed works and
 *       modifications, which include larger works using a licensed work,
 *       under the same license.
 *     • Copyright and license notices must be preserved.
 *     • Contributors provide an express grant of patent rights.
 *     • When a modified version is used to provide a service over a
 *       network, the complete source code of the modified version must be made
 *       available.
 */
package nz.org.riskscape.engine.join;

import java.util.List;
import java.util.stream.Collectors;

import lombok.Data;
import lombok.Getter;
import lombok.NonNull;
import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.types.DuplicateKeysException;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Struct.StructBuilder;
import nz.org.riskscape.engine.types.Struct.StructMember;
import nz.org.riskscape.engine.types.Type;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.ResultOrProblems;

/**
 * Can join a relation on to another relation, tuple at a time.
 */
@Data
public class Joiner implements Join {

  /**
   * Attempt to build a join from the given join parameters, returning a failed result if either the joined type or the
   * join condition are invalid.
   */
  public static ResultOrProblems<Joiner> build(Struct lhs, Struct rhs, JoinCondition on, JoinType joinType) {
    Struct joinedType;
    try {
      joinedType = buildJoined(joinType, lhs, rhs);
    } catch (DuplicateKeysException ex) {
      List<String> dups = ex.getDuplicates().stream()
          .map(d -> d.getKey())
          .collect(Collectors.toList());

      return ResultOrProblems.failed(
          Problem.error(ProblemCodes.DUPLICATE_KEYS, dups));
    }
    Joiner join = new Joiner(lhs, rhs, joinedType, on, joinType);

    List<Problem> validationErrors = on.validate(joinedType);
    if (Problem.hasErrors(validationErrors)) {
      return ResultOrProblems.failed(
          Problem.error(ProblemCodes.JOIN_CONDITION_INVALID, on, joinedType)
              .withChildren(validationErrors)
      );
    } else {
      return ResultOrProblems.of(join);
    }
  }

  private Joiner(Struct lhs, Struct rhs, JoinCondition on, JoinType joinType) throws DuplicateKeysException {
    this.lhs = lhs;
    this.rhs = rhs;
    this.on = on;
    this.joinType = joinType;
    this.joinedType = buildJoined(joinType, lhs, rhs);
  }

  private Joiner(Struct lhs, Struct rhs, Struct joinedType, JoinCondition on, JoinType joinType) {
    this.lhs = lhs;
    this.rhs = rhs;
    this.on = on;
    this.joinType = joinType;
    this.joinedType = joinedType;

  }

  public Joiner(Struct lhs, Struct rhs, JoinCondition on) {
    this(lhs, rhs, on, JoinType.INNER);
  }

  /**
   * The left-hand side of the join
   */
  @Getter
  private final Struct lhs;

  /**
   * The right-hand side of the join
   */
  @Getter
  private final Struct rhs;

  /**
   * Used to determine whether tuples should be joined or not
   */
  @NonNull @Getter
  private final JoinCondition on;

  /**
   * Whether left, inner etc
   */
  @NonNull @Getter
  private final JoinType joinType;

  @NonNull @Getter
  private final Struct joinedType;

  /**
   * @return the resulting joined type
   */
  private static Struct buildJoined(JoinType joinType, Struct lhs, Struct rhs) {
    StructBuilder builder = new StructBuilder();
    builder.addAll(lhs);
    for (StructMember member : rhs.getMembers()) {
      builder.add(member.getKey(), nullable(joinType, member.getType()));
    }
    return builder.build();
  }

  private static Type nullable(JoinType joinType, Type type) {
    if (joinType.isNullable()) {
      return Nullable.of(type);
    } else {
      return type;
    }
  }

  /**
   * Clone this join with a different {@link JoinType}
   */
  public Joiner withJoinType(JoinType newJoinType) {
    return new Joiner(lhs, rhs, on, newJoinType);
  }

  /**
   * Clone this join with a different {@link JoinCondition}
   */
  public Joiner withJoinConditon(JoinCondition newOn) {
    return new Joiner(lhs, rhs, joinedType, newOn, joinType);
  }

  /**
   * Create a joined tuple of joinedType that can be used with our joinCondition
   */
  @Override
  public Tuple join(Tuple lhsTuple, Tuple rhsTuple) {
    Tuple joined = new Tuple(this.joinedType);

    joined.setAll(lhsTuple);
    if (rhsTuple != null) {
      joined.setAll(lhs.size(), rhsTuple);
    } else if (joinType != JoinType.LEFT_OUTER) {
      throw new NullPointerException("rhs null and not a left outer join");
    }

    return joined;
  }

}
