package pgdb

import (
	"context"
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"

	dberrors "git-molva.ru/Molva/molva-backend/services/api_gateway/internal/database/errors"
	dbtypes "git-molva.ru/Molva/molva-backend/services/api_gateway/internal/database/types"
	"github.com/Masterminds/squirrel"
)

func (c *client) GetVacancyIntegrationInfoById(
	ctx context.Context,
	vacancyId string,
) (string, *dbtypes.VacancyExtraFieldsTemplate, error) {
	return c.getVacancyIntegrationInfoById(ctx, c.db, vacancyId)
}

func (c *client) getVacancyIntegrationInfoById(
	ctx context.Context,
	driver Driver,
	vacancyId string,
) (string, *dbtypes.VacancyExtraFieldsTemplate, error) {
	var (
		psql = squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar)

		vacancyTable = fmt.Sprintf("%s.%s", c.config.Schema, VacanciesTableName)
	)

	getCompanyIdQuery := psql.Select("company_id", "additional_fields").
		From(vacancyTable).
		Where(squirrel.Eq{"id": vacancyId})

	query, args, err := getCompanyIdQuery.ToSql()
	if err != nil {
		return "", nil, fmt.Errorf("%w: error building query: %v", dberrors.ErrInternal, err)
	}

	row := driver.QueryRowContext(ctx, query, args...)

	var (
		companyId    string
		fieldsString sql.NullString
		fields       dbtypes.VacancyExtraFieldsTemplate
	)

	if err := row.Scan(&companyId, &fieldsString); err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return "", nil, dberrors.ErrNotFound
		}

		return "", nil, fmt.Errorf("%w: error scanning row: %v", dberrors.ErrInternal, err)
	}

	if fieldsString.Valid {
		if err := json.Unmarshal([]byte(fieldsString.String), &fields); err != nil {
			return "", nil, fmt.Errorf("%w: error unmarshalling fields: %v", dberrors.ErrInternal, err)
		}
	}

	return companyId, &fields, nil
}

func (c *client) GetCompanyMetadataById(
	ctx context.Context,
	companyId string,
) (*dbtypes.CompanyMetadata, *dbtypes.CompanyExtraFieldsTemplate, error) {
	return c.getCompanyMetadataById(ctx, c.db, companyId)
}

func (c *client) getCompanyMetadataById(
	ctx context.Context,
	driver Driver,
	companyId string,
) (*dbtypes.CompanyMetadata, *dbtypes.CompanyExtraFieldsTemplate, error) {
	var (
		psql = squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar)

		companyTable = fmt.Sprintf("%s.%s", c.config.Schema, CompaniesTableName)
	)

	getCompanyMetadataQuery := psql.Select(
		"metadata",
		"additional_fields_tmpl",
	).
		From(companyTable).
		Where(squirrel.Eq{"id": companyId})

	query, args, err := getCompanyMetadataQuery.ToSql()
	if err != nil {
		return nil, nil, fmt.Errorf("%w: error building query: %v", dberrors.ErrInternal, err)
	}

	row := driver.QueryRowContext(ctx, query, args...)

	var (
		metadataString sql.NullString
		metadata       dbtypes.CompanyMetadata

		fieldsTemplateString sql.NullString
		fieldsTemplate       dbtypes.CompanyExtraFieldsTemplate
	)

	if err := row.Scan(&metadataString, &fieldsTemplateString); err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return nil, nil, dberrors.ErrNotFound
		}

		return nil, nil, fmt.Errorf("%w: error scanning row: %v", dberrors.ErrInternal, err)
	}

	if metadataString.Valid {
		if err := json.Unmarshal([]byte(metadataString.String), &metadata); err != nil {
			return nil, nil, fmt.Errorf("%w: error unmarshalling metadata: %v", dberrors.ErrInternal, err)
		}
	}

	if fieldsTemplateString.Valid {
		if err := json.Unmarshal([]byte(fieldsTemplateString.String), &fieldsTemplate); err != nil {
			return nil, nil, fmt.Errorf("%w: error unmarshalling fields template: %v", dberrors.ErrInternal, err)
		}
	}

	return &metadata, &fieldsTemplate, nil
}
