package com.cameleer.server.app.license;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.Timestamp;
import java.time.Instant;
import java.util.Optional;
import java.util.UUID;

public class PostgresLicenseRepository implements LicenseRepository {

    private final JdbcTemplate jdbc;

    public PostgresLicenseRepository(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }

    private static final RowMapper<LicenseRecord> MAPPER = (rs, n) -> new LicenseRecord(
            rs.getString("tenant_id"),
            rs.getString("token"),
            (UUID) rs.getObject("license_id"),
            rs.getTimestamp("installed_at").toInstant(),
            rs.getString("installed_by"),
            rs.getTimestamp("expires_at").toInstant(),
            rs.getTimestamp("last_validated_at").toInstant()
    );

    @Override
    public Optional<LicenseRecord> findByTenantId(String tenantId) {
        return jdbc.query(
                "SELECT tenant_id, token, license_id, installed_at, installed_by, expires_at, last_validated_at " +
                        "FROM license WHERE tenant_id = ?",
                MAPPER, tenantId).stream().findFirst();
    }

    @Override
    public void upsert(LicenseRecord r) {
        jdbc.update(
                "INSERT INTO license (tenant_id, token, license_id, installed_at, installed_by, expires_at, last_validated_at) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?) " +
                "ON CONFLICT (tenant_id) DO UPDATE SET " +
                "  token = EXCLUDED.token, " +
                "  license_id = EXCLUDED.license_id, " +
                "  installed_at = EXCLUDED.installed_at, " +
                "  installed_by = EXCLUDED.installed_by, " +
                "  expires_at = EXCLUDED.expires_at, " +
                "  last_validated_at = EXCLUDED.last_validated_at",
                r.tenantId(), r.token(), r.licenseId(),
                Timestamp.from(r.installedAt()), r.installedBy(),
                Timestamp.from(r.expiresAt()), Timestamp.from(r.lastValidatedAt())
        );
    }

    @Override
    public int touchValidated(String tenantId, Instant now) {
        return jdbc.update(
                "UPDATE license SET last_validated_at = ? WHERE tenant_id = ?",
                Timestamp.from(now), tenantId);
    }

    @Override
    public int delete(String tenantId) {
        return jdbc.update("DELETE FROM license WHERE tenant_id = ?", tenantId);
    }
}
